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>
26 #include <linux/log2.h>
28 #define HASH_DEFAULT_SIZE 64UL
29 #define HASH_MIN_SIZE 4UL
31 #define ASSERT_RHT_MUTEX(HT) BUG_ON(!lockdep_rht_mutex_is_held(HT))
33 #ifdef CONFIG_PROVE_LOCKING
34 int lockdep_rht_mutex_is_held(const struct rhashtable
*ht
)
36 return ht
->p
.mutex_is_held();
38 EXPORT_SYMBOL_GPL(lockdep_rht_mutex_is_held
);
41 static void *rht_obj(const struct rhashtable
*ht
, const struct rhash_head
*he
)
43 return (void *) he
- ht
->p
.head_offset
;
46 static u32
__hashfn(const struct rhashtable
*ht
, const void *key
,
51 h
= ht
->p
.hashfn(key
, len
, ht
->p
.hash_rnd
);
53 return h
& (hsize
- 1);
57 * rhashtable_hashfn - compute hash for key of given length
58 * @ht: hash table to compuate for
59 * @key: pointer to key
62 * Computes the hash value using the hash function provided in the 'hashfn'
63 * of struct rhashtable_params. The returned value is guaranteed to be
64 * smaller than the number of buckets in the hash table.
66 u32
rhashtable_hashfn(const struct rhashtable
*ht
, const void *key
, u32 len
)
68 struct bucket_table
*tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
70 return __hashfn(ht
, key
, len
, tbl
->size
);
72 EXPORT_SYMBOL_GPL(rhashtable_hashfn
);
74 static u32
obj_hashfn(const struct rhashtable
*ht
, const void *ptr
, u32 hsize
)
76 if (unlikely(!ht
->p
.key_len
)) {
79 h
= ht
->p
.obj_hashfn(ptr
, ht
->p
.hash_rnd
);
81 return h
& (hsize
- 1);
84 return __hashfn(ht
, ptr
+ ht
->p
.key_offset
, ht
->p
.key_len
, hsize
);
88 * rhashtable_obj_hashfn - compute hash for hashed object
89 * @ht: hash table to compuate for
90 * @ptr: pointer to hashed object
92 * Computes the hash value using the hash function `hashfn` respectively
93 * 'obj_hashfn' depending on whether the hash table is set up to work with
94 * a fixed length key. The returned value is guaranteed to be smaller than
95 * the number of buckets in the hash table.
97 u32
rhashtable_obj_hashfn(const struct rhashtable
*ht
, void *ptr
)
99 struct bucket_table
*tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
101 return obj_hashfn(ht
, ptr
, tbl
->size
);
103 EXPORT_SYMBOL_GPL(rhashtable_obj_hashfn
);
105 static u32
head_hashfn(const struct rhashtable
*ht
,
106 const struct rhash_head
*he
, u32 hsize
)
108 return obj_hashfn(ht
, rht_obj(ht
, he
), hsize
);
111 static struct bucket_table
*bucket_table_alloc(size_t nbuckets
, gfp_t flags
)
113 struct bucket_table
*tbl
;
116 size
= sizeof(*tbl
) + nbuckets
* sizeof(tbl
->buckets
[0]);
117 tbl
= kzalloc(size
, flags
);
124 tbl
->size
= nbuckets
;
129 static void bucket_table_free(const struct bucket_table
*tbl
)
135 * rht_grow_above_75 - returns true if nelems > 0.75 * table-size
137 * @new_size: new table size
139 bool rht_grow_above_75(const struct rhashtable
*ht
, size_t new_size
)
141 /* Expand table when exceeding 75% load */
142 return ht
->nelems
> (new_size
/ 4 * 3);
144 EXPORT_SYMBOL_GPL(rht_grow_above_75
);
147 * rht_shrink_below_30 - returns true if nelems < 0.3 * table-size
149 * @new_size: new table size
151 bool rht_shrink_below_30(const struct rhashtable
*ht
, size_t new_size
)
153 /* Shrink table beneath 30% load */
154 return ht
->nelems
< (new_size
* 3 / 10);
156 EXPORT_SYMBOL_GPL(rht_shrink_below_30
);
158 static void hashtable_chain_unzip(const struct rhashtable
*ht
,
159 const struct bucket_table
*new_tbl
,
160 struct bucket_table
*old_tbl
, size_t n
)
162 struct rhash_head
*he
, *p
, *next
;
165 /* Old bucket empty, no work needed. */
166 p
= rht_dereference(old_tbl
->buckets
[n
], ht
);
170 /* Advance the old bucket pointer one or more times until it
171 * reaches a node that doesn't hash to the same bucket as the
172 * previous node p. Call the previous node p;
174 h
= head_hashfn(ht
, p
, new_tbl
->size
);
175 rht_for_each(he
, p
->next
, ht
) {
176 if (head_hashfn(ht
, he
, new_tbl
->size
) != h
)
180 RCU_INIT_POINTER(old_tbl
->buckets
[n
], p
->next
);
182 /* Find the subsequent node which does hash to the same
183 * bucket as node P, or NULL if no such node exists.
187 rht_for_each(he
, he
->next
, ht
) {
188 if (head_hashfn(ht
, he
, new_tbl
->size
) == h
) {
195 /* Set p's next pointer to that subsequent node pointer,
196 * bypassing the nodes which do not hash to p's bucket
198 RCU_INIT_POINTER(p
->next
, next
);
202 * rhashtable_expand - Expand hash table while allowing concurrent lookups
203 * @ht: the hash table to expand
204 * @flags: allocation flags
206 * A secondary bucket array is allocated and the hash entries are migrated
207 * while keeping them on both lists until the end of the RCU grace period.
209 * This function may only be called in a context where it is safe to call
210 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
212 * The caller must ensure that no concurrent table mutations take place.
213 * It is however valid to have concurrent lookups if they are RCU protected.
215 int rhashtable_expand(struct rhashtable
*ht
, gfp_t flags
)
217 struct bucket_table
*new_tbl
, *old_tbl
= rht_dereference(ht
->tbl
, ht
);
218 struct rhash_head
*he
;
222 ASSERT_RHT_MUTEX(ht
);
224 if (ht
->p
.max_shift
&& ht
->shift
>= ht
->p
.max_shift
)
227 new_tbl
= bucket_table_alloc(old_tbl
->size
* 2, flags
);
233 /* For each new bucket, search the corresponding old bucket
234 * for the first entry that hashes to the new bucket, and
235 * link the new bucket to that entry. Since all the entries
236 * which will end up in the new bucket appear in the same
237 * old bucket, this constructs an entirely valid new hash
238 * table, but with multiple buckets "zipped" together into a
239 * single imprecise chain.
241 for (i
= 0; i
< new_tbl
->size
; i
++) {
242 h
= i
& (old_tbl
->size
- 1);
243 rht_for_each(he
, old_tbl
->buckets
[h
], ht
) {
244 if (head_hashfn(ht
, he
, new_tbl
->size
) == i
) {
245 RCU_INIT_POINTER(new_tbl
->buckets
[i
], he
);
251 /* Publish the new table pointer. Lookups may now traverse
252 * the new table, but they will not benefit from any
253 * additional efficiency until later steps unzip the buckets.
255 rcu_assign_pointer(ht
->tbl
, new_tbl
);
257 /* Unzip interleaved hash chains */
259 /* Wait for readers. All new readers will see the new
260 * table, and thus no references to the old table will
265 /* For each bucket in the old table (each of which
266 * contains items from multiple buckets of the new
270 for (i
= 0; i
< old_tbl
->size
; i
++) {
271 hashtable_chain_unzip(ht
, new_tbl
, old_tbl
, i
);
272 if (old_tbl
->buckets
[i
] != NULL
)
277 bucket_table_free(old_tbl
);
280 EXPORT_SYMBOL_GPL(rhashtable_expand
);
283 * rhashtable_shrink - Shrink hash table while allowing concurrent lookups
284 * @ht: the hash table to shrink
285 * @flags: allocation flags
287 * This function may only be called in a context where it is safe to call
288 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
290 * The caller must ensure that no concurrent table mutations take place.
291 * It is however valid to have concurrent lookups if they are RCU protected.
293 int rhashtable_shrink(struct rhashtable
*ht
, gfp_t flags
)
295 struct bucket_table
*ntbl
, *tbl
= rht_dereference(ht
->tbl
, ht
);
296 struct rhash_head __rcu
**pprev
;
299 ASSERT_RHT_MUTEX(ht
);
301 if (tbl
->size
<= HASH_MIN_SIZE
)
304 ntbl
= bucket_table_alloc(tbl
->size
/ 2, flags
);
310 /* Link each bucket in the new table to the first bucket
311 * in the old table that contains entries which will hash
314 for (i
= 0; i
< ntbl
->size
; i
++) {
315 ntbl
->buckets
[i
] = tbl
->buckets
[i
];
317 /* Link each bucket in the new table to the first bucket
318 * in the old table that contains entries which will hash
321 for (pprev
= &ntbl
->buckets
[i
]; *pprev
!= NULL
;
322 pprev
= &rht_dereference(*pprev
, ht
)->next
)
324 RCU_INIT_POINTER(*pprev
, tbl
->buckets
[i
+ ntbl
->size
]);
327 /* Publish the new, valid hash table */
328 rcu_assign_pointer(ht
->tbl
, ntbl
);
330 /* Wait for readers. No new readers will have references to the
335 bucket_table_free(tbl
);
339 EXPORT_SYMBOL_GPL(rhashtable_shrink
);
342 * rhashtable_insert - insert object into hash hash table
344 * @obj: pointer to hash head inside object
345 * @flags: allocation flags (table expansion)
347 * Will automatically grow the table via rhashtable_expand() if the the
348 * grow_decision function specified at rhashtable_init() returns true.
350 * The caller must ensure that no concurrent table mutations occur. It is
351 * however valid to have concurrent lookups if they are RCU protected.
353 void rhashtable_insert(struct rhashtable
*ht
, struct rhash_head
*obj
,
356 struct bucket_table
*tbl
= rht_dereference(ht
->tbl
, ht
);
359 ASSERT_RHT_MUTEX(ht
);
361 hash
= head_hashfn(ht
, obj
, tbl
->size
);
362 RCU_INIT_POINTER(obj
->next
, tbl
->buckets
[hash
]);
363 rcu_assign_pointer(tbl
->buckets
[hash
], obj
);
366 if (ht
->p
.grow_decision
&& ht
->p
.grow_decision(ht
, tbl
->size
))
367 rhashtable_expand(ht
, flags
);
369 EXPORT_SYMBOL_GPL(rhashtable_insert
);
372 * rhashtable_remove_pprev - remove object from hash table given previous element
374 * @obj: pointer to hash head inside object
375 * @pprev: pointer to previous element
376 * @flags: allocation flags (table expansion)
378 * Identical to rhashtable_remove() but caller is alreayd aware of the element
379 * in front of the element to be deleted. This is in particular useful for
380 * deletion when combined with walking or lookup.
382 void rhashtable_remove_pprev(struct rhashtable
*ht
, struct rhash_head
*obj
,
383 struct rhash_head __rcu
**pprev
, gfp_t flags
)
385 struct bucket_table
*tbl
= rht_dereference(ht
->tbl
, ht
);
387 ASSERT_RHT_MUTEX(ht
);
389 RCU_INIT_POINTER(*pprev
, obj
->next
);
392 if (ht
->p
.shrink_decision
&&
393 ht
->p
.shrink_decision(ht
, tbl
->size
))
394 rhashtable_shrink(ht
, flags
);
396 EXPORT_SYMBOL_GPL(rhashtable_remove_pprev
);
399 * rhashtable_remove - remove object from hash table
401 * @obj: pointer to hash head inside object
402 * @flags: allocation flags (table expansion)
404 * Since the hash chain is single linked, the removal operation needs to
405 * walk the bucket chain upon removal. The removal operation is thus
406 * considerable slow if the hash table is not correctly sized.
408 * Will automatically shrink the table via rhashtable_expand() if the the
409 * shrink_decision function specified at rhashtable_init() returns true.
411 * The caller must ensure that no concurrent table mutations occur. It is
412 * however valid to have concurrent lookups if they are RCU protected.
414 bool rhashtable_remove(struct rhashtable
*ht
, struct rhash_head
*obj
,
417 struct bucket_table
*tbl
= rht_dereference(ht
->tbl
, ht
);
418 struct rhash_head __rcu
**pprev
;
419 struct rhash_head
*he
;
422 ASSERT_RHT_MUTEX(ht
);
424 h
= head_hashfn(ht
, obj
, tbl
->size
);
426 pprev
= &tbl
->buckets
[h
];
427 rht_for_each(he
, tbl
->buckets
[h
], ht
) {
433 rhashtable_remove_pprev(ht
, he
, pprev
, flags
);
439 EXPORT_SYMBOL_GPL(rhashtable_remove
);
442 * rhashtable_lookup - lookup key in hash table
444 * @key: pointer to key
446 * Computes the hash value for the key and traverses the bucket chain looking
447 * for a entry with an identical key. The first matching entry is returned.
449 * This lookup function may only be used for fixed key hash table (key_len
450 * paramter set). It will BUG() if used inappropriately.
452 * Lookups may occur in parallel with hash mutations as long as the lookup is
453 * guarded by rcu_read_lock(). The caller must take care of this.
455 void *rhashtable_lookup(const struct rhashtable
*ht
, const void *key
)
457 const struct bucket_table
*tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
458 struct rhash_head
*he
;
461 BUG_ON(!ht
->p
.key_len
);
463 h
= __hashfn(ht
, key
, ht
->p
.key_len
, tbl
->size
);
464 rht_for_each_rcu(he
, tbl
->buckets
[h
], ht
) {
465 if (memcmp(rht_obj(ht
, he
) + ht
->p
.key_offset
, key
,
468 return (void *) he
- ht
->p
.head_offset
;
473 EXPORT_SYMBOL_GPL(rhashtable_lookup
);
476 * rhashtable_lookup_compare - search hash table with compare function
478 * @hash: hash value of desired entry
479 * @compare: compare function, must return true on match
480 * @arg: argument passed on to compare function
482 * Traverses the bucket chain behind the provided hash value and calls the
483 * specified compare function for each entry.
485 * Lookups may occur in parallel with hash mutations as long as the lookup is
486 * guarded by rcu_read_lock(). The caller must take care of this.
488 * Returns the first entry on which the compare function returned true.
490 void *rhashtable_lookup_compare(const struct rhashtable
*ht
, u32 hash
,
491 bool (*compare
)(void *, void *), void *arg
)
493 const struct bucket_table
*tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
494 struct rhash_head
*he
;
496 if (unlikely(hash
>= tbl
->size
))
499 rht_for_each_rcu(he
, tbl
->buckets
[hash
], ht
) {
500 if (!compare(rht_obj(ht
, he
), arg
))
502 return (void *) he
- ht
->p
.head_offset
;
507 EXPORT_SYMBOL_GPL(rhashtable_lookup_compare
);
509 static size_t rounded_hashtable_size(unsigned int nelem
)
511 return max(roundup_pow_of_two(nelem
* 4 / 3), HASH_MIN_SIZE
);
515 * rhashtable_init - initialize a new hash table
516 * @ht: hash table to be initialized
517 * @params: configuration parameters
519 * Initializes a new hash table based on the provided configuration
520 * parameters. A table can be configured either with a variable or
523 * Configuration Example 1: Fixed length keys
527 * struct rhash_head node;
530 * struct rhashtable_params params = {
531 * .head_offset = offsetof(struct test_obj, node),
532 * .key_offset = offsetof(struct test_obj, key),
533 * .key_len = sizeof(int),
534 * .hashfn = arch_fast_hash,
535 * .mutex_is_held = &my_mutex_is_held,
538 * Configuration Example 2: Variable length keys
541 * struct rhash_head node;
544 * u32 my_hash_fn(const void *data, u32 seed)
546 * struct test_obj *obj = data;
548 * return [... hash ...];
551 * struct rhashtable_params params = {
552 * .head_offset = offsetof(struct test_obj, node),
553 * .hashfn = arch_fast_hash,
554 * .obj_hashfn = my_hash_fn,
555 * .mutex_is_held = &my_mutex_is_held,
558 int rhashtable_init(struct rhashtable
*ht
, struct rhashtable_params
*params
)
560 struct bucket_table
*tbl
;
563 size
= HASH_DEFAULT_SIZE
;
565 if ((params
->key_len
&& !params
->hashfn
) ||
566 (!params
->key_len
&& !params
->obj_hashfn
))
569 if (params
->nelem_hint
)
570 size
= rounded_hashtable_size(params
->nelem_hint
);
572 tbl
= bucket_table_alloc(size
, GFP_KERNEL
);
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.
594 void rhashtable_destroy(const struct rhashtable
*ht
)
596 const struct bucket_table
*tbl
= rht_dereference(ht
->tbl
, ht
);
598 bucket_table_free(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 static int test_mutex_is_held(void)
621 struct rhash_head node
;
624 static int __init
test_rht_lookup(struct rhashtable
*ht
)
628 for (i
= 0; i
< TEST_ENTRIES
* 2; i
++) {
629 struct test_obj
*obj
;
630 bool expected
= !(i
% 2);
633 obj
= rhashtable_lookup(ht
, &key
);
635 if (expected
&& !obj
) {
636 pr_warn("Test failed: Could not find key %u\n", key
);
638 } else if (!expected
&& obj
) {
639 pr_warn("Test failed: Unexpected entry found for key %u\n",
642 } else if (expected
&& obj
) {
643 if (obj
->ptr
!= TEST_PTR
|| obj
->value
!= i
) {
644 pr_warn("Test failed: Lookup value mismatch %p!=%p, %u!=%u\n",
645 obj
->ptr
, TEST_PTR
, obj
->value
, i
);
654 static void test_bucket_stats(struct rhashtable
*ht
,
655 struct bucket_table
*tbl
,
658 unsigned int cnt
, i
, total
= 0;
659 struct test_obj
*obj
;
661 for (i
= 0; i
< tbl
->size
; i
++) {
665 pr_info(" [%#4x/%zu]", i
, tbl
->size
);
667 rht_for_each_entry_rcu(obj
, tbl
->buckets
[i
], node
) {
671 pr_cont(" [%p],", obj
);
675 pr_cont("\n [%#x] first element: %p, chain length: %u\n",
676 i
, tbl
->buckets
[i
], cnt
);
679 pr_info(" Traversal complete: counted=%u, nelems=%zu, entries=%d\n",
680 total
, ht
->nelems
, TEST_ENTRIES
);
683 static int __init
test_rhashtable(struct rhashtable
*ht
)
685 struct bucket_table
*tbl
;
686 struct test_obj
*obj
, *next
;
692 * Insert TEST_ENTRIES into table with all keys even numbers
694 pr_info(" Adding %d keys\n", TEST_ENTRIES
);
695 for (i
= 0; i
< TEST_ENTRIES
; i
++) {
696 struct test_obj
*obj
;
698 obj
= kzalloc(sizeof(*obj
), GFP_KERNEL
);
707 rhashtable_insert(ht
, &obj
->node
, GFP_KERNEL
);
711 tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
712 test_bucket_stats(ht
, tbl
, true);
716 for (i
= 0; i
< TEST_NEXPANDS
; i
++) {
717 pr_info(" Table expansion iteration %u...\n", i
);
718 rhashtable_expand(ht
, GFP_KERNEL
);
721 pr_info(" Verifying lookups...\n");
726 for (i
= 0; i
< TEST_NEXPANDS
; i
++) {
727 pr_info(" Table shrinkage iteration %u...\n", i
);
728 rhashtable_shrink(ht
, GFP_KERNEL
);
731 pr_info(" Verifying lookups...\n");
736 pr_info(" Deleting %d keys\n", TEST_ENTRIES
);
737 for (i
= 0; i
< TEST_ENTRIES
; i
++) {
740 obj
= rhashtable_lookup(ht
, &key
);
743 rhashtable_remove(ht
, &obj
->node
, GFP_KERNEL
);
750 tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
751 for (i
= 0; i
< tbl
->size
; i
++)
752 rht_for_each_entry_safe(obj
, next
, tbl
->buckets
[i
], ht
, node
)
758 static int __init
test_rht_init(void)
760 struct rhashtable ht
;
761 struct rhashtable_params params
= {
762 .nelem_hint
= TEST_HT_SIZE
,
763 .head_offset
= offsetof(struct test_obj
, node
),
764 .key_offset
= offsetof(struct test_obj
, value
),
765 .key_len
= sizeof(int),
766 .hashfn
= arch_fast_hash
,
767 .mutex_is_held
= &test_mutex_is_held
,
768 .grow_decision
= rht_grow_above_75
,
769 .shrink_decision
= rht_shrink_below_30
,
773 pr_info("Running resizable hashtable tests...\n");
775 err
= rhashtable_init(&ht
, ¶ms
);
777 pr_warn("Test failed: Unable to initialize hashtable: %d\n",
782 err
= test_rhashtable(&ht
);
784 rhashtable_destroy(&ht
);
789 subsys_initcall(test_rht_init
);
791 #endif /* CONFIG_TEST_RHASHTABLE */