1 // SPDX-License-Identifier: GPL-2.0-only
3 * Resizable, Scalable, Concurrent Hash Table
9 /**************************************************************************
11 **************************************************************************/
13 #include <linux/init.h>
14 #include <linux/jhash.h>
15 #include <linux/kernel.h>
16 #include <linux/kthread.h>
17 #include <linux/module.h>
18 #include <linux/rcupdate.h>
19 #include <linux/rcupdate_wait.h>
20 #include <linux/rhashtable.h>
21 #include <linux/slab.h>
22 #include <linux/sched.h>
23 #include <linux/random.h>
24 #include <linux/vmalloc.h>
25 #include <linux/wait.h>
27 #define MAX_ENTRIES 1000000
28 #define TEST_INSERT_FAIL INT_MAX
30 static int parm_entries = 50000;
31 module_param(parm_entries, int, 0);
32 MODULE_PARM_DESC(parm_entries, "Number of entries to add (default: 50000)");
35 module_param(runs, int, 0);
36 MODULE_PARM_DESC(runs, "Number of test runs per variant (default: 4)");
38 static int max_size = 0;
39 module_param(max_size, int, 0);
40 MODULE_PARM_DESC(max_size, "Maximum table size (default: calculated)");
42 static bool shrinking = false;
43 module_param(shrinking, bool, 0);
44 MODULE_PARM_DESC(shrinking, "Enable automatic shrinking (default: off)");
47 module_param(size, int, 0);
48 MODULE_PARM_DESC(size, "Initial size hint of table (default: 8)");
50 static int tcount = 10;
51 module_param(tcount, int, 0);
52 MODULE_PARM_DESC(tcount, "Number of threads to spawn (default: 10)");
54 static bool enomem_retry = false;
55 module_param(enomem_retry, bool, 0);
56 MODULE_PARM_DESC(enomem_retry, "Retry insert even if -ENOMEM was returned (default: off)");
64 struct test_obj_val value;
65 struct rhash_head node;
69 struct test_obj_val value;
70 struct rhlist_head list_node;
76 struct task_struct *task;
77 struct test_obj *objs;
80 static u32 my_hashfn(const void *data, u32 len, u32 seed)
82 const struct test_obj_rhl *obj = data;
84 return (obj->value.id % 10);
87 static int my_cmpfn(struct rhashtable_compare_arg *arg, const void *obj)
89 const struct test_obj_rhl *test_obj = obj;
90 const struct test_obj_val *val = arg->key;
92 return test_obj->value.id - val->id;
95 static struct rhashtable_params test_rht_params = {
96 .head_offset = offsetof(struct test_obj, node),
97 .key_offset = offsetof(struct test_obj, value),
98 .key_len = sizeof(struct test_obj_val),
102 static struct rhashtable_params test_rht_params_dup = {
103 .head_offset = offsetof(struct test_obj_rhl, list_node),
104 .key_offset = offsetof(struct test_obj_rhl, value),
105 .key_len = sizeof(struct test_obj_val),
107 .obj_hashfn = my_hashfn,
108 .obj_cmpfn = my_cmpfn,
110 .automatic_shrinking = false,
113 static atomic_t startup_count;
114 static DECLARE_WAIT_QUEUE_HEAD(startup_wait);
116 static int insert_retry(struct rhashtable *ht, struct test_obj *obj,
117 const struct rhashtable_params params)
119 int err, retries = -1, enomem_retries = 0;
124 err = rhashtable_insert_fast(ht, &obj->node, params);
125 if (err == -ENOMEM && enomem_retry) {
129 } while (err == -EBUSY);
132 pr_info(" %u insertions retried after -ENOMEM\n",
135 return err ? : retries;
138 static int __init test_rht_lookup(struct rhashtable *ht, struct test_obj *array,
139 unsigned int entries)
143 for (i = 0; i < entries; i++) {
144 struct test_obj *obj;
145 bool expected = !(i % 2);
146 struct test_obj_val key = {
150 if (array[i / 2].value.id == TEST_INSERT_FAIL)
153 obj = rhashtable_lookup_fast(ht, &key, test_rht_params);
155 if (expected && !obj) {
156 pr_warn("Test failed: Could not find key %u\n", key.id);
158 } else if (!expected && obj) {
159 pr_warn("Test failed: Unexpected entry found for key %u\n",
162 } else if (expected && obj) {
163 if (obj->value.id != i) {
164 pr_warn("Test failed: Lookup value mismatch %u!=%u\n",
176 static void test_bucket_stats(struct rhashtable *ht, unsigned int entries)
178 unsigned int total = 0, chain_len = 0;
179 struct rhashtable_iter hti;
180 struct rhash_head *pos;
182 rhashtable_walk_enter(ht, &hti);
183 rhashtable_walk_start(&hti);
185 while ((pos = rhashtable_walk_next(&hti))) {
186 if (PTR_ERR(pos) == -EAGAIN) {
187 pr_info("Info: encountered resize\n");
190 } else if (IS_ERR(pos)) {
191 pr_warn("Test failed: rhashtable_walk_next() error: %ld\n",
199 rhashtable_walk_stop(&hti);
200 rhashtable_walk_exit(&hti);
202 pr_info(" Traversal complete: counted=%u, nelems=%u, entries=%d, table-jumps=%u\n",
203 total, atomic_read(&ht->nelems), entries, chain_len);
205 if (total != atomic_read(&ht->nelems) || total != entries)
206 pr_warn("Test failed: Total count mismatch ^^^");
209 static s64 __init test_rhashtable(struct rhashtable *ht, struct test_obj *array,
210 unsigned int entries)
212 struct test_obj *obj;
214 unsigned int i, insert_retries = 0;
219 * Insert entries into table with all keys even numbers
221 pr_info(" Adding %d keys\n", entries);
222 start = ktime_get_ns();
223 for (i = 0; i < entries; i++) {
224 struct test_obj *obj = &array[i];
226 obj->value.id = i * 2;
227 err = insert_retry(ht, obj, test_rht_params);
229 insert_retries += err;
235 pr_info(" %u insertions retried due to memory pressure\n",
238 test_bucket_stats(ht, entries);
240 test_rht_lookup(ht, array, entries);
243 test_bucket_stats(ht, entries);
245 pr_info(" Deleting %d keys\n", entries);
246 for (i = 0; i < entries; i++) {
247 struct test_obj_val key = {
251 if (array[i].value.id != TEST_INSERT_FAIL) {
252 obj = rhashtable_lookup_fast(ht, &key, test_rht_params);
255 rhashtable_remove_fast(ht, &obj->node, test_rht_params);
261 end = ktime_get_ns();
262 pr_info(" Duration of test: %lld ns\n", end - start);
267 static struct rhashtable ht;
268 static struct rhltable rhlt;
270 static int __init test_rhltable(unsigned int entries)
272 struct test_obj_rhl *rhl_test_objects;
273 unsigned long *obj_in_table;
274 unsigned int i, j, k;
280 rhl_test_objects = vzalloc(array_size(entries,
281 sizeof(*rhl_test_objects)));
282 if (!rhl_test_objects)
286 obj_in_table = vzalloc(array_size(sizeof(unsigned long),
287 BITS_TO_LONGS(entries)));
291 err = rhltable_init(&rhlt, &test_rht_params);
295 k = get_random_u32();
297 for (i = 0; i < entries; i++) {
298 rhl_test_objects[i].value.id = k;
299 err = rhltable_insert(&rhlt, &rhl_test_objects[i].list_node,
301 if (WARN(err, "error %d on element %d\n", err, i))
304 set_bit(i, obj_in_table);
310 pr_info("test %d add/delete pairs into rhlist\n", entries);
311 for (i = 0; i < entries; i++) {
312 struct rhlist_head *h, *pos;
313 struct test_obj_rhl *obj;
314 struct test_obj_val key = {
320 h = rhltable_lookup(&rhlt, &key, test_rht_params);
321 if (WARN(!h, "key not found during iteration %d of %d", i, entries)) {
328 rhl_for_each_entry_rcu(obj, pos, h, list_node) {
329 if (WARN(pos == &rhl_test_objects[j].list_node, "old element found, should be gone"))
338 rhl_for_each_entry_rcu(obj, pos, h, list_node) {
339 if (pos == &rhl_test_objects[i].list_node) {
347 if (WARN(!found, "element %d not found", i))
350 err = rhltable_remove(&rhlt, &rhl_test_objects[i].list_node, test_rht_params);
351 WARN(err, "rhltable_remove: err %d for iteration %d\n", err, i);
353 clear_bit(i, obj_in_table);
359 for (i = 0; i < entries; i++) {
360 WARN(test_bit(i, obj_in_table), "elem %d allegedly still present", i);
362 err = rhltable_insert(&rhlt, &rhl_test_objects[i].list_node,
364 if (WARN(err, "error %d on element %d\n", err, i))
367 set_bit(i, obj_in_table);
370 pr_info("test %d random rhlist add/delete operations\n", entries);
371 for (j = 0; j < entries; j++) {
372 u32 i = get_random_u32_below(entries);
373 u32 prand = get_random_u32_below(4);
377 err = rhltable_remove(&rhlt, &rhl_test_objects[i].list_node, test_rht_params);
378 if (test_bit(i, obj_in_table)) {
379 clear_bit(i, obj_in_table);
380 if (WARN(err, "cannot remove element at slot %d", i))
383 if (WARN(err != -ENOENT, "removed non-existent element %d, error %d not %d",
389 err = rhltable_insert(&rhlt, &rhl_test_objects[i].list_node, test_rht_params);
391 if (WARN(test_and_set_bit(i, obj_in_table), "succeeded to insert same object %d", i))
394 if (WARN(!test_bit(i, obj_in_table), "failed to insert object %d", i))
400 i = get_random_u32_below(entries);
401 if (test_bit(i, obj_in_table)) {
402 err = rhltable_remove(&rhlt, &rhl_test_objects[i].list_node, test_rht_params);
403 WARN(err, "cannot remove element at slot %d", i);
405 clear_bit(i, obj_in_table);
407 err = rhltable_insert(&rhlt, &rhl_test_objects[i].list_node, test_rht_params);
408 WARN(err, "failed to insert object %d", i);
410 set_bit(i, obj_in_table);
415 for (i = 0; i < entries; i++) {
417 err = rhltable_remove(&rhlt, &rhl_test_objects[i].list_node, test_rht_params);
418 if (test_bit(i, obj_in_table)) {
419 if (WARN(err, "cannot remove element at slot %d", i))
422 if (WARN(err != -ENOENT, "removed non-existent element, error %d not %d",
428 rhltable_destroy(&rhlt);
430 vfree(rhl_test_objects);
435 static int __init test_rhashtable_max(struct test_obj *array,
436 unsigned int entries)
441 test_rht_params.max_size = roundup_pow_of_two(entries / 8);
442 err = rhashtable_init(&ht, &test_rht_params);
446 for (i = 0; i < ht.max_elems; i++) {
447 struct test_obj *obj = &array[i];
449 obj->value.id = i * 2;
450 err = insert_retry(&ht, obj, test_rht_params);
455 err = insert_retry(&ht, &array[ht.max_elems], test_rht_params);
459 pr_info("insert element %u should have failed with %d, got %d\n",
460 ht.max_elems, -E2BIG, err);
465 rhashtable_destroy(&ht);
470 static unsigned int __init print_ht(struct rhltable *rhlt)
472 struct rhashtable *ht;
473 const struct bucket_table *tbl;
476 unsigned int i, cnt = 0;
479 /* Take the mutex to avoid RCU warning */
480 mutex_lock(&ht->mutex);
481 tbl = rht_dereference(ht->tbl, ht);
482 for (i = 0; i < tbl->size; i++) {
483 struct rhash_head *pos, *next;
484 struct test_obj_rhl *p;
486 pos = rht_ptr_exclusive(tbl->buckets + i);
487 next = !rht_is_a_nulls(pos) ? rht_dereference(pos->next, ht) : NULL;
489 if (!rht_is_a_nulls(pos)) {
490 offset += sprintf(buff + offset, "\nbucket[%d] -> ", i);
493 while (!rht_is_a_nulls(pos)) {
494 struct rhlist_head *list = container_of(pos, struct rhlist_head, rhead);
495 offset += sprintf(buff + offset, "[[");
498 list = rht_dereference(list->next, ht);
499 p = rht_obj(ht, pos);
501 offset += sprintf(buff + offset, " val %d (tid=%d)%s", p->value.id, p->value.tid,
507 next = !rht_is_a_nulls(pos) ?
508 rht_dereference(pos->next, ht) : NULL;
510 offset += sprintf(buff + offset, "]]%s", !rht_is_a_nulls(pos) ? " -> " : "");
513 printk(KERN_ERR "\n---- ht: ----%s\n-------------\n", buff);
514 mutex_unlock(&ht->mutex);
519 static int __init test_insert_dup(struct test_obj_rhl *rhl_test_objects,
522 struct rhltable *rhlt;
527 rhlt = kmalloc(sizeof(*rhlt), GFP_KERNEL);
531 err = rhltable_init(rhlt, &test_rht_params_dup);
537 for (i = 0; i < cnt; i++) {
538 rhl_test_objects[i].value.tid = i;
539 key = rht_obj(&rhlt->ht, &rhl_test_objects[i].list_node.rhead);
540 key += test_rht_params_dup.key_offset;
543 err = PTR_ERR(rhashtable_insert_slow(&rhlt->ht, key,
544 &rhl_test_objects[i].list_node.rhead));
548 err = rhltable_insert(rhlt,
549 &rhl_test_objects[i].list_node,
550 test_rht_params_dup);
551 if (WARN(err, "error %d on element %d/%d (%s)\n", err, i, cnt, slow? "slow" : "fast"))
555 ret = print_ht(rhlt);
556 WARN(ret != cnt, "missing rhltable elements (%d != %d, %s)\n", ret, cnt, slow? "slow" : "fast");
559 rhltable_destroy(rhlt);
565 static int __init test_insert_duplicates_run(void)
567 struct test_obj_rhl rhl_test_objects[3] = {};
569 pr_info("test inserting duplicates\n");
571 /* two different values that map to same bucket */
572 rhl_test_objects[0].value.id = 1;
573 rhl_test_objects[1].value.id = 21;
575 /* and another duplicate with same as [0] value
576 * which will be second on the bucket list */
577 rhl_test_objects[2].value.id = rhl_test_objects[0].value.id;
579 test_insert_dup(rhl_test_objects, 2, false);
580 test_insert_dup(rhl_test_objects, 3, false);
581 test_insert_dup(rhl_test_objects, 2, true);
582 test_insert_dup(rhl_test_objects, 3, true);
587 static int thread_lookup_test(struct thread_data *tdata)
589 unsigned int entries = tdata->entries;
592 for (i = 0; i < entries; i++) {
593 struct test_obj *obj;
594 struct test_obj_val key = {
599 obj = rhashtable_lookup_fast(&ht, &key, test_rht_params);
600 if (obj && (tdata->objs[i].value.id == TEST_INSERT_FAIL)) {
601 pr_err(" found unexpected object %d-%d\n", key.tid, key.id);
603 } else if (!obj && (tdata->objs[i].value.id != TEST_INSERT_FAIL)) {
604 pr_err(" object %d-%d not found!\n", key.tid, key.id);
606 } else if (obj && memcmp(&obj->value, &key, sizeof(key))) {
607 pr_err(" wrong object returned (got %d-%d, expected %d-%d)\n",
608 obj->value.tid, obj->value.id, key.tid, key.id);
617 static int threadfunc(void *data)
619 int i, step, err = 0, insert_retries = 0;
620 struct thread_data *tdata = data;
622 if (atomic_dec_and_test(&startup_count))
623 wake_up(&startup_wait);
624 if (wait_event_interruptible(startup_wait, atomic_read(&startup_count) == -1)) {
625 pr_err(" thread[%d]: interrupted\n", tdata->id);
629 for (i = 0; i < tdata->entries; i++) {
630 tdata->objs[i].value.id = i;
631 tdata->objs[i].value.tid = tdata->id;
632 err = insert_retry(&ht, &tdata->objs[i], test_rht_params);
634 insert_retries += err;
636 pr_err(" thread[%d]: rhashtable_insert_fast failed\n",
642 pr_info(" thread[%d]: %u insertions retried due to memory pressure\n",
643 tdata->id, insert_retries);
645 err = thread_lookup_test(tdata);
647 pr_err(" thread[%d]: rhashtable_lookup_test failed\n",
652 for (step = 10; step > 0; step--) {
653 for (i = 0; i < tdata->entries; i += step) {
654 if (tdata->objs[i].value.id == TEST_INSERT_FAIL)
656 err = rhashtable_remove_fast(&ht, &tdata->objs[i].node,
659 pr_err(" thread[%d]: rhashtable_remove_fast failed\n",
663 tdata->objs[i].value.id = TEST_INSERT_FAIL;
667 err = thread_lookup_test(tdata);
669 pr_err(" thread[%d]: rhashtable_lookup_test (2) failed\n",
675 while (!kthread_should_stop()) {
676 set_current_state(TASK_INTERRUPTIBLE);
682 static int __init test_rht_init(void)
684 unsigned int entries;
685 int i, err, started_threads = 0, failed_threads = 0;
687 struct thread_data *tdata;
688 struct test_obj *objs;
690 if (parm_entries < 0)
693 entries = min(parm_entries, MAX_ENTRIES);
695 test_rht_params.automatic_shrinking = shrinking;
696 test_rht_params.max_size = max_size ? : roundup_pow_of_two(entries);
697 test_rht_params.nelem_hint = size;
699 objs = vzalloc(array_size(sizeof(struct test_obj),
700 test_rht_params.max_size + 1));
704 pr_info("Running rhashtable test nelem=%d, max_size=%d, shrinking=%d\n",
705 size, max_size, shrinking);
707 for (i = 0; i < runs; i++) {
710 pr_info("Test %02d:\n", i);
711 memset(objs, 0, test_rht_params.max_size * sizeof(struct test_obj));
713 err = rhashtable_init(&ht, &test_rht_params);
715 pr_warn("Test failed: Unable to initialize hashtable: %d\n",
720 time = test_rhashtable(&ht, objs, entries);
721 rhashtable_destroy(&ht);
724 pr_warn("Test failed: return code %lld\n", time);
731 pr_info("test if its possible to exceed max_size %d: %s\n",
732 test_rht_params.max_size, test_rhashtable_max(objs, entries) == 0 ?
733 "no, ok" : "YES, failed");
736 do_div(total_time, runs);
737 pr_info("Average test time: %llu\n", total_time);
739 test_insert_duplicates_run();
744 pr_info("Testing concurrent rhashtable access from %d threads\n",
746 atomic_set(&startup_count, tcount);
747 tdata = vzalloc(array_size(tcount, sizeof(struct thread_data)));
750 objs = vzalloc(array3_size(sizeof(struct test_obj), tcount, entries));
756 test_rht_params.max_size = max_size ? :
757 roundup_pow_of_two(tcount * entries);
758 err = rhashtable_init(&ht, &test_rht_params);
760 pr_warn("Test failed: Unable to initialize hashtable: %d\n",
766 for (i = 0; i < tcount; i++) {
768 tdata[i].entries = entries;
769 tdata[i].objs = objs + i * entries;
770 tdata[i].task = kthread_run(threadfunc, &tdata[i],
771 "rhashtable_thrad[%d]", i);
772 if (IS_ERR(tdata[i].task)) {
773 pr_err(" kthread_run failed for thread %d\n", i);
774 atomic_dec(&startup_count);
779 if (wait_event_interruptible(startup_wait, atomic_read(&startup_count) == 0))
780 pr_err(" wait_event interruptible failed\n");
781 /* count is 0 now, set it to -1 and wake up all threads together */
782 atomic_dec(&startup_count);
783 wake_up_all(&startup_wait);
784 for (i = 0; i < tcount; i++) {
785 if (IS_ERR(tdata[i].task))
787 if ((err = kthread_stop(tdata[i].task))) {
788 pr_warn("Test failed: thread %d returned: %d\n",
793 rhashtable_destroy(&ht);
798 * rhltable_remove is very expensive, default values can cause test
799 * to run for 2 minutes or more, use a smaller number instead.
801 err = test_rhltable(entries / 16);
802 pr_info("Started %d threads, %d failed, rhltable test returns %d\n",
803 started_threads, failed_threads, err);
807 static void __exit test_rht_exit(void)
811 module_init(test_rht_init);
812 module_exit(test_rht_exit);
814 MODULE_LICENSE("GPL v2");