2 * Resizable, Scalable, Concurrent Hash Table
4 * Copyright (c) 2015 Herbert Xu <herbert@gondor.apana.org.au>
5 * Copyright (c) 2014-2015 Thomas Graf <tgraf@suug.ch>
6 * Copyright (c) 2008-2014 Patrick McHardy <kaber@trash.net>
8 * Code partially derived from nft_hash
9 * Rewritten with rehash code from br_multicast plus single list
10 * pointer as suggested by Josh Triplett
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/atomic.h>
18 #include <linux/kernel.h>
19 #include <linux/init.h>
20 #include <linux/log2.h>
21 #include <linux/sched.h>
22 #include <linux/slab.h>
23 #include <linux/vmalloc.h>
25 #include <linux/jhash.h>
26 #include <linux/random.h>
27 #include <linux/rhashtable.h>
28 #include <linux/err.h>
29 #include <linux/export.h>
31 #define HASH_DEFAULT_SIZE 64UL
32 #define HASH_MIN_SIZE 4U
33 #define BUCKET_LOCKS_PER_CPU 128UL
35 static u32 head_hashfn(struct rhashtable *ht,
36 const struct bucket_table *tbl,
37 const struct rhash_head *he)
39 return rht_head_hashfn(ht, tbl, he, ht->p);
42 #ifdef CONFIG_PROVE_LOCKING
43 #define ASSERT_RHT_MUTEX(HT) BUG_ON(!lockdep_rht_mutex_is_held(HT))
45 int lockdep_rht_mutex_is_held(struct rhashtable *ht)
47 return (debug_locks) ? lockdep_is_held(&ht->mutex) : 1;
49 EXPORT_SYMBOL_GPL(lockdep_rht_mutex_is_held);
51 int lockdep_rht_bucket_is_held(const struct bucket_table *tbl, u32 hash)
53 spinlock_t *lock = rht_bucket_lock(tbl, hash);
55 return (debug_locks) ? lockdep_is_held(lock) : 1;
57 EXPORT_SYMBOL_GPL(lockdep_rht_bucket_is_held);
59 #define ASSERT_RHT_MUTEX(HT)
63 static int alloc_bucket_locks(struct rhashtable *ht, struct bucket_table *tbl,
67 #if defined(CONFIG_PROVE_LOCKING)
68 unsigned int nr_pcpus = 2;
70 unsigned int nr_pcpus = num_possible_cpus();
73 nr_pcpus = min_t(unsigned int, nr_pcpus, 32UL);
74 size = roundup_pow_of_two(nr_pcpus * ht->p.locks_mul);
76 /* Never allocate more than 0.5 locks per bucket */
77 size = min_t(unsigned int, size, tbl->size >> 1);
79 if (sizeof(spinlock_t) != 0) {
81 if (size * sizeof(spinlock_t) > PAGE_SIZE &&
83 tbl->locks = vmalloc(size * sizeof(spinlock_t));
86 tbl->locks = kmalloc_array(size, sizeof(spinlock_t),
90 for (i = 0; i < size; i++)
91 spin_lock_init(&tbl->locks[i]);
93 tbl->locks_mask = size - 1;
98 static void bucket_table_free(const struct bucket_table *tbl)
106 static void bucket_table_free_rcu(struct rcu_head *head)
108 bucket_table_free(container_of(head, struct bucket_table, rcu));
111 static struct bucket_table *bucket_table_alloc(struct rhashtable *ht,
115 struct bucket_table *tbl = NULL;
119 size = sizeof(*tbl) + nbuckets * sizeof(tbl->buckets[0]);
120 if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER) ||
122 tbl = kzalloc(size, gfp | __GFP_NOWARN | __GFP_NORETRY);
123 if (tbl == NULL && gfp == GFP_KERNEL)
128 tbl->size = nbuckets;
130 if (alloc_bucket_locks(ht, tbl, gfp) < 0) {
131 bucket_table_free(tbl);
135 INIT_LIST_HEAD(&tbl->walkers);
137 get_random_bytes(&tbl->hash_rnd, sizeof(tbl->hash_rnd));
139 for (i = 0; i < nbuckets; i++)
140 INIT_RHT_NULLS_HEAD(tbl->buckets[i], ht, i);
145 static struct bucket_table *rhashtable_last_table(struct rhashtable *ht,
146 struct bucket_table *tbl)
148 struct bucket_table *new_tbl;
152 tbl = rht_dereference_rcu(tbl->future_tbl, ht);
158 static int rhashtable_rehash_one(struct rhashtable *ht, unsigned int old_hash)
160 struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht);
161 struct bucket_table *new_tbl = rhashtable_last_table(ht,
162 rht_dereference_rcu(old_tbl->future_tbl, ht));
163 struct rhash_head __rcu **pprev = &old_tbl->buckets[old_hash];
165 struct rhash_head *head, *next, *entry;
166 spinlock_t *new_bucket_lock;
167 unsigned int new_hash;
169 rht_for_each(entry, old_tbl, old_hash) {
171 next = rht_dereference_bucket(entry->next, old_tbl, old_hash);
173 if (rht_is_a_nulls(next))
176 pprev = &entry->next;
182 new_hash = head_hashfn(ht, new_tbl, entry);
184 new_bucket_lock = rht_bucket_lock(new_tbl, new_hash);
186 spin_lock_nested(new_bucket_lock, SINGLE_DEPTH_NESTING);
187 head = rht_dereference_bucket(new_tbl->buckets[new_hash],
190 RCU_INIT_POINTER(entry->next, head);
192 rcu_assign_pointer(new_tbl->buckets[new_hash], entry);
193 spin_unlock(new_bucket_lock);
195 rcu_assign_pointer(*pprev, next);
201 static void rhashtable_rehash_chain(struct rhashtable *ht,
202 unsigned int old_hash)
204 struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht);
205 spinlock_t *old_bucket_lock;
207 old_bucket_lock = rht_bucket_lock(old_tbl, old_hash);
209 spin_lock_bh(old_bucket_lock);
210 while (!rhashtable_rehash_one(ht, old_hash))
213 spin_unlock_bh(old_bucket_lock);
216 static int rhashtable_rehash_attach(struct rhashtable *ht,
217 struct bucket_table *old_tbl,
218 struct bucket_table *new_tbl)
220 /* Protect future_tbl using the first bucket lock. */
221 spin_lock_bh(old_tbl->locks);
223 /* Did somebody beat us to it? */
224 if (rcu_access_pointer(old_tbl->future_tbl)) {
225 spin_unlock_bh(old_tbl->locks);
229 /* Make insertions go into the new, empty table right away. Deletions
230 * and lookups will be attempted in both tables until we synchronize.
232 rcu_assign_pointer(old_tbl->future_tbl, new_tbl);
234 /* Ensure the new table is visible to readers. */
237 spin_unlock_bh(old_tbl->locks);
242 static int rhashtable_rehash_table(struct rhashtable *ht)
244 struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht);
245 struct bucket_table *new_tbl;
246 struct rhashtable_walker *walker;
247 unsigned int old_hash;
249 new_tbl = rht_dereference(old_tbl->future_tbl, ht);
253 for (old_hash = 0; old_hash < old_tbl->size; old_hash++)
254 rhashtable_rehash_chain(ht, old_hash);
256 /* Publish the new table pointer. */
257 rcu_assign_pointer(ht->tbl, new_tbl);
259 spin_lock(&ht->lock);
260 list_for_each_entry(walker, &old_tbl->walkers, list)
262 spin_unlock(&ht->lock);
264 /* Wait for readers. All new readers will see the new
265 * table, and thus no references to the old table will
268 call_rcu(&old_tbl->rcu, bucket_table_free_rcu);
270 return rht_dereference(new_tbl->future_tbl, ht) ? -EAGAIN : 0;
274 * rhashtable_expand - Expand hash table while allowing concurrent lookups
275 * @ht: the hash table to expand
277 * A secondary bucket array is allocated and the hash entries are migrated.
279 * This function may only be called in a context where it is safe to call
280 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
282 * The caller must ensure that no concurrent resizing occurs by holding
285 * It is valid to have concurrent insertions and deletions protected by per
286 * bucket locks or concurrent RCU protected lookups and traversals.
288 static int rhashtable_expand(struct rhashtable *ht)
290 struct bucket_table *new_tbl, *old_tbl = rht_dereference(ht->tbl, ht);
293 ASSERT_RHT_MUTEX(ht);
295 old_tbl = rhashtable_last_table(ht, old_tbl);
297 new_tbl = bucket_table_alloc(ht, old_tbl->size * 2, GFP_KERNEL);
301 err = rhashtable_rehash_attach(ht, old_tbl, new_tbl);
303 bucket_table_free(new_tbl);
309 * rhashtable_shrink - Shrink hash table while allowing concurrent lookups
310 * @ht: the hash table to shrink
312 * This function shrinks the hash table to fit, i.e., the smallest
313 * size would not cause it to expand right away automatically.
315 * The caller must ensure that no concurrent resizing occurs by holding
318 * The caller must ensure that no concurrent table mutations take place.
319 * It is however valid to have concurrent lookups if they are RCU protected.
321 * It is valid to have concurrent insertions and deletions protected by per
322 * bucket locks or concurrent RCU protected lookups and traversals.
324 static int rhashtable_shrink(struct rhashtable *ht)
326 struct bucket_table *new_tbl, *old_tbl = rht_dereference(ht->tbl, ht);
330 ASSERT_RHT_MUTEX(ht);
332 size = roundup_pow_of_two(atomic_read(&ht->nelems) * 3 / 2);
333 if (size < ht->p.min_size)
334 size = ht->p.min_size;
336 if (old_tbl->size <= size)
339 if (rht_dereference(old_tbl->future_tbl, ht))
342 new_tbl = bucket_table_alloc(ht, size, GFP_KERNEL);
346 err = rhashtable_rehash_attach(ht, old_tbl, new_tbl);
348 bucket_table_free(new_tbl);
353 static void rht_deferred_worker(struct work_struct *work)
355 struct rhashtable *ht;
356 struct bucket_table *tbl;
359 ht = container_of(work, struct rhashtable, run_work);
360 mutex_lock(&ht->mutex);
362 tbl = rht_dereference(ht->tbl, ht);
363 tbl = rhashtable_last_table(ht, tbl);
365 if (rht_grow_above_75(ht, tbl))
366 rhashtable_expand(ht);
367 else if (ht->p.automatic_shrinking && rht_shrink_below_30(ht, tbl))
368 rhashtable_shrink(ht);
370 err = rhashtable_rehash_table(ht);
372 mutex_unlock(&ht->mutex);
375 schedule_work(&ht->run_work);
378 static bool rhashtable_check_elasticity(struct rhashtable *ht,
379 struct bucket_table *tbl,
382 unsigned int elasticity = ht->elasticity;
383 struct rhash_head *head;
385 rht_for_each(head, tbl, hash)
392 int rhashtable_insert_rehash(struct rhashtable *ht,
393 struct bucket_table *tbl)
395 struct bucket_table *old_tbl;
396 struct bucket_table *new_tbl;
400 old_tbl = rht_dereference_rcu(ht->tbl, ht);
406 if (rht_grow_above_75(ht, tbl))
408 /* Do not schedule more than one rehash */
409 else if (old_tbl != tbl)
414 new_tbl = bucket_table_alloc(ht, size, GFP_ATOMIC);
418 err = rhashtable_rehash_attach(ht, tbl, new_tbl);
420 bucket_table_free(new_tbl);
424 schedule_work(&ht->run_work);
429 /* Do not fail the insert if someone else did a rehash. */
430 if (likely(rcu_dereference_raw(tbl->future_tbl)))
433 /* Schedule async rehash to retry allocation in process context. */
435 schedule_work(&ht->run_work);
439 EXPORT_SYMBOL_GPL(rhashtable_insert_rehash);
441 struct bucket_table *rhashtable_insert_slow(struct rhashtable *ht,
443 struct rhash_head *obj,
444 struct bucket_table *tbl)
446 struct rhash_head *head;
450 tbl = rhashtable_last_table(ht, tbl);
451 hash = head_hashfn(ht, tbl, obj);
452 spin_lock_nested(rht_bucket_lock(tbl, hash), SINGLE_DEPTH_NESTING);
455 if (key && rhashtable_lookup_fast(ht, key, ht->p))
459 if (unlikely(rht_grow_above_max(ht, tbl)))
463 if (rhashtable_check_elasticity(ht, tbl, hash) ||
464 rht_grow_above_100(ht, tbl))
469 head = rht_dereference_bucket(tbl->buckets[hash], tbl, hash);
471 RCU_INIT_POINTER(obj->next, head);
473 rcu_assign_pointer(tbl->buckets[hash], obj);
475 atomic_inc(&ht->nelems);
478 spin_unlock(rht_bucket_lock(tbl, hash));
482 else if (err == -EAGAIN)
487 EXPORT_SYMBOL_GPL(rhashtable_insert_slow);
490 * rhashtable_walk_init - Initialise an iterator
491 * @ht: Table to walk over
492 * @iter: Hash table Iterator
494 * This function prepares a hash table walk.
496 * Note that if you restart a walk after rhashtable_walk_stop you
497 * may see the same object twice. Also, you may miss objects if
498 * there are removals in between rhashtable_walk_stop and the next
499 * call to rhashtable_walk_start.
501 * For a completely stable walk you should construct your own data
502 * structure outside the hash table.
504 * This function may sleep so you must not call it from interrupt
505 * context or with spin locks held.
507 * You must call rhashtable_walk_exit if this function returns
510 int rhashtable_walk_init(struct rhashtable *ht, struct rhashtable_iter *iter)
517 iter->walker = kmalloc(sizeof(*iter->walker), GFP_KERNEL);
521 spin_lock(&ht->lock);
523 rcu_dereference_protected(ht->tbl, lockdep_is_held(&ht->lock));
524 list_add(&iter->walker->list, &iter->walker->tbl->walkers);
525 spin_unlock(&ht->lock);
529 EXPORT_SYMBOL_GPL(rhashtable_walk_init);
532 * rhashtable_walk_exit - Free an iterator
533 * @iter: Hash table Iterator
535 * This function frees resources allocated by rhashtable_walk_init.
537 void rhashtable_walk_exit(struct rhashtable_iter *iter)
539 spin_lock(&iter->ht->lock);
540 if (iter->walker->tbl)
541 list_del(&iter->walker->list);
542 spin_unlock(&iter->ht->lock);
545 EXPORT_SYMBOL_GPL(rhashtable_walk_exit);
548 * rhashtable_walk_start - Start a hash table walk
549 * @iter: Hash table iterator
551 * Start a hash table walk. Note that we take the RCU lock in all
552 * cases including when we return an error. So you must always call
553 * rhashtable_walk_stop to clean up.
555 * Returns zero if successful.
557 * Returns -EAGAIN if resize event occured. Note that the iterator
558 * will rewind back to the beginning and you may use it immediately
559 * by calling rhashtable_walk_next.
561 int rhashtable_walk_start(struct rhashtable_iter *iter)
564 struct rhashtable *ht = iter->ht;
568 spin_lock(&ht->lock);
569 if (iter->walker->tbl)
570 list_del(&iter->walker->list);
571 spin_unlock(&ht->lock);
573 if (!iter->walker->tbl) {
574 iter->walker->tbl = rht_dereference_rcu(ht->tbl, ht);
580 EXPORT_SYMBOL_GPL(rhashtable_walk_start);
583 * rhashtable_walk_next - Return the next object and advance the iterator
584 * @iter: Hash table iterator
586 * Note that you must call rhashtable_walk_stop when you are finished
589 * Returns the next object or NULL when the end of the table is reached.
591 * Returns -EAGAIN if resize event occured. Note that the iterator
592 * will rewind back to the beginning and you may continue to use it.
594 void *rhashtable_walk_next(struct rhashtable_iter *iter)
596 struct bucket_table *tbl = iter->walker->tbl;
597 struct rhashtable *ht = iter->ht;
598 struct rhash_head *p = iter->p;
601 p = rht_dereference_bucket_rcu(p->next, tbl, iter->slot);
605 for (; iter->slot < tbl->size; iter->slot++) {
606 int skip = iter->skip;
608 rht_for_each_rcu(p, tbl, iter->slot) {
615 if (!rht_is_a_nulls(p)) {
618 return rht_obj(ht, p);
626 /* Ensure we see any new tables. */
629 iter->walker->tbl = rht_dereference_rcu(tbl->future_tbl, ht);
630 if (iter->walker->tbl) {
633 return ERR_PTR(-EAGAIN);
638 EXPORT_SYMBOL_GPL(rhashtable_walk_next);
641 * rhashtable_walk_stop - Finish a hash table walk
642 * @iter: Hash table iterator
644 * Finish a hash table walk.
646 void rhashtable_walk_stop(struct rhashtable_iter *iter)
649 struct rhashtable *ht;
650 struct bucket_table *tbl = iter->walker->tbl;
657 spin_lock(&ht->lock);
658 if (tbl->rehash < tbl->size)
659 list_add(&iter->walker->list, &tbl->walkers);
661 iter->walker->tbl = NULL;
662 spin_unlock(&ht->lock);
669 EXPORT_SYMBOL_GPL(rhashtable_walk_stop);
671 static size_t rounded_hashtable_size(const struct rhashtable_params *params)
673 return max(roundup_pow_of_two(params->nelem_hint * 4 / 3),
674 (unsigned long)params->min_size);
677 static u32 rhashtable_jhash2(const void *key, u32 length, u32 seed)
679 return jhash2(key, length, seed);
683 * rhashtable_init - initialize a new hash table
684 * @ht: hash table to be initialized
685 * @params: configuration parameters
687 * Initializes a new hash table based on the provided configuration
688 * parameters. A table can be configured either with a variable or
691 * Configuration Example 1: Fixed length keys
695 * struct rhash_head node;
698 * struct rhashtable_params params = {
699 * .head_offset = offsetof(struct test_obj, node),
700 * .key_offset = offsetof(struct test_obj, key),
701 * .key_len = sizeof(int),
703 * .nulls_base = (1U << RHT_BASE_SHIFT),
706 * Configuration Example 2: Variable length keys
709 * struct rhash_head node;
712 * u32 my_hash_fn(const void *data, u32 len, u32 seed)
714 * struct test_obj *obj = data;
716 * return [... hash ...];
719 * struct rhashtable_params params = {
720 * .head_offset = offsetof(struct test_obj, node),
722 * .obj_hashfn = my_hash_fn,
725 int rhashtable_init(struct rhashtable *ht,
726 const struct rhashtable_params *params)
728 struct bucket_table *tbl;
731 size = HASH_DEFAULT_SIZE;
733 if ((!params->key_len && !params->obj_hashfn) ||
734 (params->obj_hashfn && !params->obj_cmpfn))
737 if (params->nulls_base && params->nulls_base < (1U << RHT_BASE_SHIFT))
740 memset(ht, 0, sizeof(*ht));
741 mutex_init(&ht->mutex);
742 spin_lock_init(&ht->lock);
743 memcpy(&ht->p, params, sizeof(*params));
745 if (params->min_size)
746 ht->p.min_size = roundup_pow_of_two(params->min_size);
748 if (params->max_size)
749 ht->p.max_size = rounddown_pow_of_two(params->max_size);
751 if (params->insecure_max_entries)
752 ht->p.insecure_max_entries =
753 rounddown_pow_of_two(params->insecure_max_entries);
755 ht->p.insecure_max_entries = ht->p.max_size * 2;
757 ht->p.min_size = max(ht->p.min_size, HASH_MIN_SIZE);
759 if (params->nelem_hint)
760 size = rounded_hashtable_size(&ht->p);
762 /* The maximum (not average) chain length grows with the
763 * size of the hash table, at a rate of (log N)/(log log N).
764 * The value of 16 is selected so that even if the hash
765 * table grew to 2^32 you would not expect the maximum
766 * chain length to exceed it unless we are under attack
767 * (or extremely unlucky).
769 * As this limit is only to detect attacks, we don't need
770 * to set it to a lower value as you'd need the chain
771 * length to vastly exceed 16 to have any real effect
774 if (!params->insecure_elasticity)
777 if (params->locks_mul)
778 ht->p.locks_mul = roundup_pow_of_two(params->locks_mul);
780 ht->p.locks_mul = BUCKET_LOCKS_PER_CPU;
782 ht->key_len = ht->p.key_len;
783 if (!params->hashfn) {
784 ht->p.hashfn = jhash;
786 if (!(ht->key_len & (sizeof(u32) - 1))) {
787 ht->key_len /= sizeof(u32);
788 ht->p.hashfn = rhashtable_jhash2;
792 tbl = bucket_table_alloc(ht, size, GFP_KERNEL);
796 atomic_set(&ht->nelems, 0);
798 RCU_INIT_POINTER(ht->tbl, tbl);
800 INIT_WORK(&ht->run_work, rht_deferred_worker);
804 EXPORT_SYMBOL_GPL(rhashtable_init);
807 * rhashtable_free_and_destroy - free elements and destroy hash table
808 * @ht: the hash table to destroy
809 * @free_fn: callback to release resources of element
810 * @arg: pointer passed to free_fn
812 * Stops an eventual async resize. If defined, invokes free_fn for each
813 * element to releasal resources. Please note that RCU protected
814 * readers may still be accessing the elements. Releasing of resources
815 * must occur in a compatible manner. Then frees the bucket array.
817 * This function will eventually sleep to wait for an async resize
818 * to complete. The caller is responsible that no further write operations
819 * occurs in parallel.
821 void rhashtable_free_and_destroy(struct rhashtable *ht,
822 void (*free_fn)(void *ptr, void *arg),
825 const struct bucket_table *tbl;
828 cancel_work_sync(&ht->run_work);
830 mutex_lock(&ht->mutex);
831 tbl = rht_dereference(ht->tbl, ht);
833 for (i = 0; i < tbl->size; i++) {
834 struct rhash_head *pos, *next;
836 for (pos = rht_dereference(tbl->buckets[i], ht),
837 next = !rht_is_a_nulls(pos) ?
838 rht_dereference(pos->next, ht) : NULL;
839 !rht_is_a_nulls(pos);
841 next = !rht_is_a_nulls(pos) ?
842 rht_dereference(pos->next, ht) : NULL)
843 free_fn(rht_obj(ht, pos), arg);
847 bucket_table_free(tbl);
848 mutex_unlock(&ht->mutex);
850 EXPORT_SYMBOL_GPL(rhashtable_free_and_destroy);
852 void rhashtable_destroy(struct rhashtable *ht)
854 return rhashtable_free_and_destroy(ht, NULL, NULL);
856 EXPORT_SYMBOL_GPL(rhashtable_destroy);