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);
39 int lockdep_rht_bucket_is_held(const struct bucket_table *tbl, u32 hash)
43 EXPORT_SYMBOL_GPL(lockdep_rht_bucket_is_held);
46 static void *rht_obj(const struct rhashtable *ht, const struct rhash_head *he)
48 return (void *) he - ht->p.head_offset;
51 static u32 rht_bucket_index(const struct bucket_table *tbl, u32 hash)
53 return hash & (tbl->size - 1);
56 static u32 obj_raw_hashfn(const struct rhashtable *ht, const void *ptr)
60 if (unlikely(!ht->p.key_len))
61 hash = ht->p.obj_hashfn(ptr, ht->p.hash_rnd);
63 hash = ht->p.hashfn(ptr + ht->p.key_offset, ht->p.key_len,
69 static u32 key_hashfn(const struct rhashtable *ht, const void *key, u32 len)
71 struct bucket_table *tbl = rht_dereference_rcu(ht->tbl, ht);
74 hash = ht->p.hashfn(key, len, ht->p.hash_rnd);
76 return rht_bucket_index(tbl, hash);
79 static u32 head_hashfn(const struct rhashtable *ht,
80 const struct bucket_table *tbl,
81 const struct rhash_head *he)
83 return rht_bucket_index(tbl, obj_raw_hashfn(ht, rht_obj(ht, he)));
86 static struct rhash_head __rcu **bucket_tail(struct bucket_table *tbl, u32 n)
88 struct rhash_head __rcu **pprev;
90 for (pprev = &tbl->buckets[n];
91 rht_dereference_bucket(*pprev, tbl, n);
92 pprev = &rht_dereference_bucket(*pprev, tbl, n)->next)
98 static struct bucket_table *bucket_table_alloc(size_t nbuckets)
100 struct bucket_table *tbl;
103 size = sizeof(*tbl) + nbuckets * sizeof(tbl->buckets[0]);
104 tbl = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
111 tbl->size = nbuckets;
116 static void bucket_table_free(const struct bucket_table *tbl)
122 * rht_grow_above_75 - returns true if nelems > 0.75 * table-size
124 * @new_size: new table size
126 bool rht_grow_above_75(const struct rhashtable *ht, size_t new_size)
128 /* Expand table when exceeding 75% load */
129 return ht->nelems > (new_size / 4 * 3);
131 EXPORT_SYMBOL_GPL(rht_grow_above_75);
134 * rht_shrink_below_30 - returns true if nelems < 0.3 * table-size
136 * @new_size: new table size
138 bool rht_shrink_below_30(const struct rhashtable *ht, size_t new_size)
140 /* Shrink table beneath 30% load */
141 return ht->nelems < (new_size * 3 / 10);
143 EXPORT_SYMBOL_GPL(rht_shrink_below_30);
145 static void hashtable_chain_unzip(const struct rhashtable *ht,
146 const struct bucket_table *new_tbl,
147 struct bucket_table *old_tbl, size_t n)
149 struct rhash_head *he, *p, *next;
152 /* Old bucket empty, no work needed. */
153 p = rht_dereference(old_tbl->buckets[n], ht);
157 /* Advance the old bucket pointer one or more times until it
158 * reaches a node that doesn't hash to the same bucket as the
159 * previous node p. Call the previous node p;
161 h = head_hashfn(ht, new_tbl, p);
162 rht_for_each_continue(he, p->next, old_tbl, n) {
163 if (head_hashfn(ht, new_tbl, he) != h)
167 RCU_INIT_POINTER(old_tbl->buckets[n], p->next);
169 /* Find the subsequent node which does hash to the same
170 * bucket as node P, or NULL if no such node exists.
174 rht_for_each_continue(he, he->next, old_tbl, n) {
175 if (head_hashfn(ht, new_tbl, he) == h) {
182 /* Set p's next pointer to that subsequent node pointer,
183 * bypassing the nodes which do not hash to p's bucket
185 RCU_INIT_POINTER(p->next, next);
189 * rhashtable_expand - Expand hash table while allowing concurrent lookups
190 * @ht: the hash table to expand
192 * A secondary bucket array is allocated and the hash entries are migrated
193 * while keeping them on both lists until the end of the RCU grace period.
195 * This function may only be called in a context where it is safe to call
196 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
198 * The caller must ensure that no concurrent table mutations take place.
199 * It is however valid to have concurrent lookups if they are RCU protected.
201 int rhashtable_expand(struct rhashtable *ht)
203 struct bucket_table *new_tbl, *old_tbl = rht_dereference(ht->tbl, ht);
204 struct rhash_head *he;
208 ASSERT_RHT_MUTEX(ht);
210 if (ht->p.max_shift && ht->shift >= ht->p.max_shift)
213 new_tbl = bucket_table_alloc(old_tbl->size * 2);
219 /* For each new bucket, search the corresponding old bucket
220 * for the first entry that hashes to the new bucket, and
221 * link the new bucket to that entry. Since all the entries
222 * which will end up in the new bucket appear in the same
223 * old bucket, this constructs an entirely valid new hash
224 * table, but with multiple buckets "zipped" together into a
225 * single imprecise chain.
227 for (i = 0; i < new_tbl->size; i++) {
228 h = rht_bucket_index(old_tbl, i);
229 rht_for_each(he, old_tbl, h) {
230 if (head_hashfn(ht, new_tbl, he) == i) {
231 RCU_INIT_POINTER(new_tbl->buckets[i], he);
237 /* Publish the new table pointer. Lookups may now traverse
238 * the new table, but they will not benefit from any
239 * additional efficiency until later steps unzip the buckets.
241 rcu_assign_pointer(ht->tbl, new_tbl);
243 /* Unzip interleaved hash chains */
245 /* Wait for readers. All new readers will see the new
246 * table, and thus no references to the old table will
251 /* For each bucket in the old table (each of which
252 * contains items from multiple buckets of the new
256 for (i = 0; i < old_tbl->size; i++) {
257 hashtable_chain_unzip(ht, new_tbl, old_tbl, i);
258 if (old_tbl->buckets[i] != NULL)
263 bucket_table_free(old_tbl);
266 EXPORT_SYMBOL_GPL(rhashtable_expand);
269 * rhashtable_shrink - Shrink hash table while allowing concurrent lookups
270 * @ht: the hash table to shrink
272 * This function may only be called in a context where it is safe to call
273 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
275 * The caller must ensure that no concurrent table mutations take place.
276 * It is however valid to have concurrent lookups if they are RCU protected.
278 int rhashtable_shrink(struct rhashtable *ht)
280 struct bucket_table *ntbl, *tbl = rht_dereference(ht->tbl, ht);
283 ASSERT_RHT_MUTEX(ht);
285 if (ht->shift <= ht->p.min_shift)
288 ntbl = bucket_table_alloc(tbl->size / 2);
294 /* Link each bucket in the new table to the first bucket
295 * in the old table that contains entries which will hash
298 for (i = 0; i < ntbl->size; i++) {
299 ntbl->buckets[i] = tbl->buckets[i];
300 RCU_INIT_POINTER(*bucket_tail(ntbl, i),
301 tbl->buckets[i + ntbl->size]);
305 /* Publish the new, valid hash table */
306 rcu_assign_pointer(ht->tbl, ntbl);
308 /* Wait for readers. No new readers will have references to the
313 bucket_table_free(tbl);
317 EXPORT_SYMBOL_GPL(rhashtable_shrink);
320 * rhashtable_insert - insert object into hash hash table
322 * @obj: pointer to hash head inside object
324 * Will automatically grow the table via rhashtable_expand() if the the
325 * grow_decision function specified at rhashtable_init() returns true.
327 * The caller must ensure that no concurrent table mutations occur. It is
328 * however valid to have concurrent lookups if they are RCU protected.
330 void rhashtable_insert(struct rhashtable *ht, struct rhash_head *obj)
332 struct bucket_table *tbl = rht_dereference(ht->tbl, ht);
335 ASSERT_RHT_MUTEX(ht);
337 hash = head_hashfn(ht, tbl, obj);
338 RCU_INIT_POINTER(obj->next, tbl->buckets[hash]);
339 rcu_assign_pointer(tbl->buckets[hash], obj);
342 if (ht->p.grow_decision && ht->p.grow_decision(ht, tbl->size))
343 rhashtable_expand(ht);
345 EXPORT_SYMBOL_GPL(rhashtable_insert);
348 * rhashtable_remove - remove object from hash table
350 * @obj: pointer to hash head inside object
352 * Since the hash chain is single linked, the removal operation needs to
353 * walk the bucket chain upon removal. The removal operation is thus
354 * considerable slow if the hash table is not correctly sized.
356 * Will automatically shrink the table via rhashtable_expand() if the the
357 * shrink_decision function specified at rhashtable_init() returns true.
359 * The caller must ensure that no concurrent table mutations occur. It is
360 * however valid to have concurrent lookups if they are RCU protected.
362 bool rhashtable_remove(struct rhashtable *ht, struct rhash_head *obj)
364 struct bucket_table *tbl = rht_dereference(ht->tbl, ht);
365 struct rhash_head __rcu **pprev;
366 struct rhash_head *he;
369 ASSERT_RHT_MUTEX(ht);
371 h = head_hashfn(ht, tbl, obj);
373 pprev = &tbl->buckets[h];
374 rht_for_each(he, tbl, h) {
380 RCU_INIT_POINTER(*pprev, he->next);
383 if (ht->p.shrink_decision &&
384 ht->p.shrink_decision(ht, tbl->size))
385 rhashtable_shrink(ht);
392 EXPORT_SYMBOL_GPL(rhashtable_remove);
395 * rhashtable_lookup - lookup key in hash table
397 * @key: pointer to key
399 * Computes the hash value for the key and traverses the bucket chain looking
400 * for a entry with an identical key. The first matching entry is returned.
402 * This lookup function may only be used for fixed key hash table (key_len
403 * paramter set). It will BUG() if used inappropriately.
405 * Lookups may occur in parallel with hash mutations as long as the lookup is
406 * guarded by rcu_read_lock(). The caller must take care of this.
408 void *rhashtable_lookup(const struct rhashtable *ht, const void *key)
410 const struct bucket_table *tbl = rht_dereference_rcu(ht->tbl, ht);
411 struct rhash_head *he;
414 BUG_ON(!ht->p.key_len);
416 h = key_hashfn(ht, key, ht->p.key_len);
417 rht_for_each_rcu(he, tbl, h) {
418 if (memcmp(rht_obj(ht, he) + ht->p.key_offset, key,
421 return rht_obj(ht, he);
426 EXPORT_SYMBOL_GPL(rhashtable_lookup);
429 * rhashtable_lookup_compare - search hash table with compare function
431 * @key: the pointer to the key
432 * @compare: compare function, must return true on match
433 * @arg: argument passed on to compare function
435 * Traverses the bucket chain behind the provided hash value and calls the
436 * specified compare function for each entry.
438 * Lookups may occur in parallel with hash mutations as long as the lookup is
439 * guarded by rcu_read_lock(). The caller must take care of this.
441 * Returns the first entry on which the compare function returned true.
443 void *rhashtable_lookup_compare(const struct rhashtable *ht, const void *key,
444 bool (*compare)(void *, void *), void *arg)
446 const struct bucket_table *tbl = rht_dereference_rcu(ht->tbl, ht);
447 struct rhash_head *he;
450 hash = key_hashfn(ht, key, ht->p.key_len);
451 rht_for_each_rcu(he, tbl, hash) {
452 if (!compare(rht_obj(ht, he), arg))
454 return rht_obj(ht, he);
459 EXPORT_SYMBOL_GPL(rhashtable_lookup_compare);
461 static size_t rounded_hashtable_size(struct rhashtable_params *params)
463 return max(roundup_pow_of_two(params->nelem_hint * 4 / 3),
464 1UL << params->min_shift);
468 * rhashtable_init - initialize a new hash table
469 * @ht: hash table to be initialized
470 * @params: configuration parameters
472 * Initializes a new hash table based on the provided configuration
473 * parameters. A table can be configured either with a variable or
476 * Configuration Example 1: Fixed length keys
480 * struct rhash_head node;
483 * struct rhashtable_params params = {
484 * .head_offset = offsetof(struct test_obj, node),
485 * .key_offset = offsetof(struct test_obj, key),
486 * .key_len = sizeof(int),
488 * #ifdef CONFIG_PROVE_LOCKING
489 * .mutex_is_held = &my_mutex_is_held,
493 * Configuration Example 2: Variable length keys
496 * struct rhash_head node;
499 * u32 my_hash_fn(const void *data, u32 seed)
501 * struct test_obj *obj = data;
503 * return [... hash ...];
506 * struct rhashtable_params params = {
507 * .head_offset = offsetof(struct test_obj, node),
509 * .obj_hashfn = my_hash_fn,
510 * #ifdef CONFIG_PROVE_LOCKING
511 * .mutex_is_held = &my_mutex_is_held,
515 int rhashtable_init(struct rhashtable *ht, struct rhashtable_params *params)
517 struct bucket_table *tbl;
520 size = HASH_DEFAULT_SIZE;
522 if ((params->key_len && !params->hashfn) ||
523 (!params->key_len && !params->obj_hashfn))
526 params->min_shift = max_t(size_t, params->min_shift,
527 ilog2(HASH_MIN_SIZE));
529 if (params->nelem_hint)
530 size = rounded_hashtable_size(params);
532 tbl = bucket_table_alloc(size);
536 memset(ht, 0, sizeof(*ht));
537 ht->shift = ilog2(tbl->size);
538 memcpy(&ht->p, params, sizeof(*params));
539 RCU_INIT_POINTER(ht->tbl, tbl);
542 get_random_bytes(&ht->p.hash_rnd, sizeof(ht->p.hash_rnd));
546 EXPORT_SYMBOL_GPL(rhashtable_init);
549 * rhashtable_destroy - destroy hash table
550 * @ht: the hash table to destroy
552 * Frees the bucket array. This function is not rcu safe, therefore the caller
553 * has to make sure that no resizing may happen by unpublishing the hashtable
554 * and waiting for the quiescent cycle before releasing the bucket array.
556 void rhashtable_destroy(const struct rhashtable *ht)
558 bucket_table_free(ht->tbl);
560 EXPORT_SYMBOL_GPL(rhashtable_destroy);
562 /**************************************************************************
564 **************************************************************************/
566 #ifdef CONFIG_TEST_RHASHTABLE
568 #define TEST_HT_SIZE 8
569 #define TEST_ENTRIES 2048
570 #define TEST_PTR ((void *) 0xdeadbeef)
571 #define TEST_NEXPANDS 4
573 #ifdef CONFIG_PROVE_LOCKING
574 static int test_mutex_is_held(void *parent)
583 struct rhash_head node;
586 static int __init test_rht_lookup(struct rhashtable *ht)
590 for (i = 0; i < TEST_ENTRIES * 2; i++) {
591 struct test_obj *obj;
592 bool expected = !(i % 2);
595 obj = rhashtable_lookup(ht, &key);
597 if (expected && !obj) {
598 pr_warn("Test failed: Could not find key %u\n", key);
600 } else if (!expected && obj) {
601 pr_warn("Test failed: Unexpected entry found for key %u\n",
604 } else if (expected && obj) {
605 if (obj->ptr != TEST_PTR || obj->value != i) {
606 pr_warn("Test failed: Lookup value mismatch %p!=%p, %u!=%u\n",
607 obj->ptr, TEST_PTR, obj->value, i);
616 static void test_bucket_stats(struct rhashtable *ht, bool quiet)
618 unsigned int cnt, rcu_cnt, i, total = 0;
619 struct rhash_head *pos;
620 struct test_obj *obj;
621 struct bucket_table *tbl;
623 tbl = rht_dereference_rcu(ht->tbl, ht);
624 for (i = 0; i < tbl->size; i++) {
628 pr_info(" [%#4x/%zu]", i, tbl->size);
630 rht_for_each_entry_rcu(obj, pos, tbl, i, node) {
634 pr_cont(" [%p],", obj);
637 rht_for_each_entry_rcu(obj, pos, tbl, i, node)
641 pr_warn("Test failed: Chain count mismach %d != %d",
645 pr_cont("\n [%#x] first element: %p, chain length: %u\n",
646 i, tbl->buckets[i], cnt);
649 pr_info(" Traversal complete: counted=%u, nelems=%zu, entries=%d\n",
650 total, ht->nelems, TEST_ENTRIES);
652 if (total != ht->nelems || total != TEST_ENTRIES)
653 pr_warn("Test failed: Total count mismatch ^^^");
656 static int __init test_rhashtable(struct rhashtable *ht)
658 struct bucket_table *tbl;
659 struct test_obj *obj;
660 struct rhash_head *pos, *next;
666 * Insert TEST_ENTRIES into table with all keys even numbers
668 pr_info(" Adding %d keys\n", TEST_ENTRIES);
669 for (i = 0; i < TEST_ENTRIES; i++) {
670 struct test_obj *obj;
672 obj = kzalloc(sizeof(*obj), GFP_KERNEL);
681 rhashtable_insert(ht, &obj->node);
685 test_bucket_stats(ht, true);
689 for (i = 0; i < TEST_NEXPANDS; i++) {
690 pr_info(" Table expansion iteration %u...\n", i);
691 rhashtable_expand(ht);
694 pr_info(" Verifying lookups...\n");
699 for (i = 0; i < TEST_NEXPANDS; i++) {
700 pr_info(" Table shrinkage iteration %u...\n", i);
701 rhashtable_shrink(ht);
704 pr_info(" Verifying lookups...\n");
710 test_bucket_stats(ht, true);
713 pr_info(" Deleting %d keys\n", TEST_ENTRIES);
714 for (i = 0; i < TEST_ENTRIES; i++) {
717 obj = rhashtable_lookup(ht, &key);
720 rhashtable_remove(ht, &obj->node);
727 tbl = rht_dereference_rcu(ht->tbl, ht);
728 for (i = 0; i < tbl->size; i++)
729 rht_for_each_entry_safe(obj, pos, next, tbl, i, node)
735 static int __init test_rht_init(void)
737 struct rhashtable ht;
738 struct rhashtable_params params = {
739 .nelem_hint = TEST_HT_SIZE,
740 .head_offset = offsetof(struct test_obj, node),
741 .key_offset = offsetof(struct test_obj, value),
742 .key_len = sizeof(int),
744 #ifdef CONFIG_PROVE_LOCKING
745 .mutex_is_held = &test_mutex_is_held,
747 .grow_decision = rht_grow_above_75,
748 .shrink_decision = rht_shrink_below_30,
752 pr_info("Running resizable hashtable tests...\n");
754 err = rhashtable_init(&ht, ¶ms);
756 pr_warn("Test failed: Unable to initialize hashtable: %d\n",
761 err = test_rhashtable(&ht);
763 rhashtable_destroy(&ht);
768 subsys_initcall(test_rht_init);
770 #endif /* CONFIG_TEST_RHASHTABLE */