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
29 #define BUCKET_LOCKS_PER_CPU 128UL
31 /* Base bits plus 1 bit for nulls marker */
32 #define HASH_RESERVED_SPACE (RHT_BASE_BITS + 1)
40 /* The bucket lock is selected based on the hash and protects mutations
41 * on a group of hash buckets.
43 * IMPORTANT: When holding the bucket lock of both the old and new table
44 * during expansions and shrinking, the old bucket lock must always be
47 static spinlock_t *bucket_lock(const struct bucket_table *tbl, u32 hash)
49 return &tbl->locks[hash & tbl->locks_mask];
52 #define ASSERT_RHT_MUTEX(HT) BUG_ON(!lockdep_rht_mutex_is_held(HT))
53 #define ASSERT_BUCKET_LOCK(TBL, HASH) \
54 BUG_ON(!lockdep_rht_bucket_is_held(TBL, HASH))
56 #ifdef CONFIG_PROVE_LOCKING
57 int lockdep_rht_mutex_is_held(struct rhashtable *ht)
59 return (debug_locks) ? lockdep_is_held(&ht->mutex) : 1;
61 EXPORT_SYMBOL_GPL(lockdep_rht_mutex_is_held);
63 int lockdep_rht_bucket_is_held(const struct bucket_table *tbl, u32 hash)
65 spinlock_t *lock = bucket_lock(tbl, hash);
67 return (debug_locks) ? lockdep_is_held(lock) : 1;
69 EXPORT_SYMBOL_GPL(lockdep_rht_bucket_is_held);
72 static void *rht_obj(const struct rhashtable *ht, const struct rhash_head *he)
74 return (void *) he - ht->p.head_offset;
77 static u32 rht_bucket_index(const struct bucket_table *tbl, u32 hash)
79 return hash & (tbl->size - 1);
82 static u32 obj_raw_hashfn(const struct rhashtable *ht, const void *ptr)
86 if (unlikely(!ht->p.key_len))
87 hash = ht->p.obj_hashfn(ptr, ht->p.hash_rnd);
89 hash = ht->p.hashfn(ptr + ht->p.key_offset, ht->p.key_len,
92 return hash >> HASH_RESERVED_SPACE;
95 static u32 key_hashfn(struct rhashtable *ht, const void *key, u32 len)
97 return ht->p.hashfn(key, len, ht->p.hash_rnd) >> HASH_RESERVED_SPACE;
100 static u32 head_hashfn(const struct rhashtable *ht,
101 const struct bucket_table *tbl,
102 const struct rhash_head *he)
104 return rht_bucket_index(tbl, obj_raw_hashfn(ht, rht_obj(ht, he)));
107 static struct rhash_head __rcu **bucket_tail(struct bucket_table *tbl, u32 n)
109 struct rhash_head __rcu **pprev;
111 for (pprev = &tbl->buckets[n];
112 !rht_is_a_nulls(rht_dereference_bucket(*pprev, tbl, n));
113 pprev = &rht_dereference_bucket(*pprev, tbl, n)->next)
119 static int alloc_bucket_locks(struct rhashtable *ht, struct bucket_table *tbl)
121 unsigned int i, size;
122 #if defined(CONFIG_PROVE_LOCKING)
123 unsigned int nr_pcpus = 2;
125 unsigned int nr_pcpus = num_possible_cpus();
128 nr_pcpus = min_t(unsigned int, nr_pcpus, 32UL);
129 size = roundup_pow_of_two(nr_pcpus * ht->p.locks_mul);
131 /* Never allocate more than one lock per bucket */
132 size = min_t(unsigned int, size, tbl->size);
134 if (sizeof(spinlock_t) != 0) {
136 if (size * sizeof(spinlock_t) > PAGE_SIZE)
137 tbl->locks = vmalloc(size * sizeof(spinlock_t));
140 tbl->locks = kmalloc_array(size, sizeof(spinlock_t),
144 for (i = 0; i < size; i++)
145 spin_lock_init(&tbl->locks[i]);
147 tbl->locks_mask = size - 1;
152 static void bucket_table_free(const struct bucket_table *tbl)
160 static struct bucket_table *bucket_table_alloc(struct rhashtable *ht,
163 struct bucket_table *tbl;
167 size = sizeof(*tbl) + nbuckets * sizeof(tbl->buckets[0]);
168 tbl = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
175 tbl->size = nbuckets;
177 if (alloc_bucket_locks(ht, tbl) < 0) {
178 bucket_table_free(tbl);
182 for (i = 0; i < nbuckets; i++)
183 INIT_RHT_NULLS_HEAD(tbl->buckets[i], ht, i);
189 * rht_grow_above_75 - returns true if nelems > 0.75 * table-size
191 * @new_size: new table size
193 bool rht_grow_above_75(const struct rhashtable *ht, size_t new_size)
195 /* Expand table when exceeding 75% load */
196 return atomic_read(&ht->nelems) > (new_size / 4 * 3) &&
197 (ht->p.max_shift && atomic_read(&ht->shift) < ht->p.max_shift);
199 EXPORT_SYMBOL_GPL(rht_grow_above_75);
202 * rht_shrink_below_30 - returns true if nelems < 0.3 * table-size
204 * @new_size: new table size
206 bool rht_shrink_below_30(const struct rhashtable *ht, size_t new_size)
208 /* Shrink table beneath 30% load */
209 return atomic_read(&ht->nelems) < (new_size * 3 / 10) &&
210 (atomic_read(&ht->shift) > ht->p.min_shift);
212 EXPORT_SYMBOL_GPL(rht_shrink_below_30);
214 static void hashtable_chain_unzip(const struct rhashtable *ht,
215 const struct bucket_table *new_tbl,
216 struct bucket_table *old_tbl,
219 struct rhash_head *he, *p, *next;
220 spinlock_t *new_bucket_lock, *new_bucket_lock2 = NULL;
221 unsigned int new_hash, new_hash2;
223 ASSERT_BUCKET_LOCK(old_tbl, old_hash);
225 /* Old bucket empty, no work needed. */
226 p = rht_dereference_bucket(old_tbl->buckets[old_hash], old_tbl,
228 if (rht_is_a_nulls(p))
231 new_hash = new_hash2 = head_hashfn(ht, new_tbl, p);
232 new_bucket_lock = bucket_lock(new_tbl, new_hash);
234 /* Advance the old bucket pointer one or more times until it
235 * reaches a node that doesn't hash to the same bucket as the
236 * previous node p. Call the previous node p;
238 rht_for_each_continue(he, p->next, old_tbl, old_hash) {
239 new_hash2 = head_hashfn(ht, new_tbl, he);
240 if (new_hash != new_hash2)
244 rcu_assign_pointer(old_tbl->buckets[old_hash], p->next);
246 spin_lock_bh_nested(new_bucket_lock, RHT_LOCK_NESTED);
248 /* If we have encountered an entry that maps to a different bucket in
249 * the new table, lock down that bucket as well as we might cut off
250 * the end of the chain.
252 new_bucket_lock2 = bucket_lock(new_tbl, new_hash);
253 if (new_bucket_lock != new_bucket_lock2)
254 spin_lock_bh_nested(new_bucket_lock2, RHT_LOCK_NESTED2);
256 /* Find the subsequent node which does hash to the same
257 * bucket as node P, or NULL if no such node exists.
259 INIT_RHT_NULLS_HEAD(next, ht, old_hash);
260 if (!rht_is_a_nulls(he)) {
261 rht_for_each_continue(he, he->next, old_tbl, old_hash) {
262 if (head_hashfn(ht, new_tbl, he) == new_hash) {
269 /* Set p's next pointer to that subsequent node pointer,
270 * bypassing the nodes which do not hash to p's bucket
272 rcu_assign_pointer(p->next, next);
274 if (new_bucket_lock != new_bucket_lock2)
275 spin_unlock_bh(new_bucket_lock2);
276 spin_unlock_bh(new_bucket_lock);
279 static void link_old_to_new(struct bucket_table *new_tbl,
280 unsigned int new_hash, struct rhash_head *entry)
282 spinlock_t *new_bucket_lock;
284 new_bucket_lock = bucket_lock(new_tbl, new_hash);
286 spin_lock_bh_nested(new_bucket_lock, RHT_LOCK_NESTED);
287 rcu_assign_pointer(*bucket_tail(new_tbl, new_hash), entry);
288 spin_unlock_bh(new_bucket_lock);
292 * rhashtable_expand - Expand hash table while allowing concurrent lookups
293 * @ht: the hash table to expand
295 * A secondary bucket array is allocated and the hash entries are migrated
296 * while keeping them on both lists until the end of the RCU grace period.
298 * This function may only be called in a context where it is safe to call
299 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
301 * The caller must ensure that no concurrent resizing occurs by holding
304 * It is valid to have concurrent insertions and deletions protected by per
305 * bucket locks or concurrent RCU protected lookups and traversals.
307 int rhashtable_expand(struct rhashtable *ht)
309 struct bucket_table *new_tbl, *old_tbl = rht_dereference(ht->tbl, ht);
310 struct rhash_head *he;
311 spinlock_t *old_bucket_lock;
312 unsigned int new_hash, old_hash;
313 bool complete = false;
315 ASSERT_RHT_MUTEX(ht);
317 new_tbl = bucket_table_alloc(ht, old_tbl->size * 2);
321 atomic_inc(&ht->shift);
323 /* Make insertions go into the new, empty table right away. Deletions
324 * and lookups will be attempted in both tables until we synchronize.
325 * The synchronize_rcu() guarantees for the new table to be picked up
326 * so no new additions go into the old table while we relink.
328 rcu_assign_pointer(ht->future_tbl, new_tbl);
331 /* For each new bucket, search the corresponding old bucket for the
332 * first entry that hashes to the new bucket, and link the end of
333 * newly formed bucket chain (containing entries added to future
334 * table) to that entry. Since all the entries which will end up in
335 * the new bucket appear in the same old bucket, this constructs an
336 * entirely valid new hash table, but with multiple buckets
337 * "zipped" together into a single imprecise chain.
339 for (new_hash = 0; new_hash < new_tbl->size; new_hash++) {
340 old_hash = rht_bucket_index(old_tbl, new_hash);
341 old_bucket_lock = bucket_lock(old_tbl, old_hash);
343 spin_lock_bh(old_bucket_lock);
344 rht_for_each(he, old_tbl, old_hash) {
345 if (head_hashfn(ht, new_tbl, he) == new_hash) {
346 link_old_to_new(new_tbl, new_hash, he);
350 spin_unlock_bh(old_bucket_lock);
353 /* Publish the new table pointer. Lookups may now traverse
354 * the new table, but they will not benefit from any
355 * additional efficiency until later steps unzip the buckets.
357 rcu_assign_pointer(ht->tbl, new_tbl);
359 /* Unzip interleaved hash chains */
360 while (!complete && !ht->being_destroyed) {
361 /* Wait for readers. All new readers will see the new
362 * table, and thus no references to the old table will
367 /* For each bucket in the old table (each of which
368 * contains items from multiple buckets of the new
372 for (old_hash = 0; old_hash < old_tbl->size; old_hash++) {
373 struct rhash_head *head;
375 old_bucket_lock = bucket_lock(old_tbl, old_hash);
376 spin_lock_bh(old_bucket_lock);
378 hashtable_chain_unzip(ht, new_tbl, old_tbl, old_hash);
379 head = rht_dereference_bucket(old_tbl->buckets[old_hash],
381 if (!rht_is_a_nulls(head))
384 spin_unlock_bh(old_bucket_lock);
388 bucket_table_free(old_tbl);
391 EXPORT_SYMBOL_GPL(rhashtable_expand);
394 * rhashtable_shrink - Shrink hash table while allowing concurrent lookups
395 * @ht: the hash table to shrink
397 * This function may only be called in a context where it is safe to call
398 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
400 * The caller must ensure that no concurrent resizing occurs by holding
403 * The caller must ensure that no concurrent table mutations take place.
404 * It is however valid to have concurrent lookups if they are RCU protected.
406 * It is valid to have concurrent insertions and deletions protected by per
407 * bucket locks or concurrent RCU protected lookups and traversals.
409 int rhashtable_shrink(struct rhashtable *ht)
411 struct bucket_table *new_tbl, *tbl = rht_dereference(ht->tbl, ht);
412 spinlock_t *new_bucket_lock, *old_bucket_lock1, *old_bucket_lock2;
413 unsigned int new_hash;
415 ASSERT_RHT_MUTEX(ht);
417 new_tbl = bucket_table_alloc(ht, tbl->size / 2);
421 rcu_assign_pointer(ht->future_tbl, new_tbl);
424 /* Link the first entry in the old bucket to the end of the
425 * bucket in the new table. As entries are concurrently being
426 * added to the new table, lock down the new bucket. As we
427 * always divide the size in half when shrinking, each bucket
428 * in the new table maps to exactly two buckets in the old
431 * As removals can occur concurrently on the old table, we need
432 * to lock down both matching buckets in the old table.
434 for (new_hash = 0; new_hash < new_tbl->size; new_hash++) {
435 old_bucket_lock1 = bucket_lock(tbl, new_hash);
436 old_bucket_lock2 = bucket_lock(tbl, new_hash + new_tbl->size);
437 new_bucket_lock = bucket_lock(new_tbl, new_hash);
439 spin_lock_bh(old_bucket_lock1);
441 /* Depending on the lock per buckets mapping, the bucket in
442 * the lower and upper region may map to the same lock.
444 if (old_bucket_lock1 != old_bucket_lock2) {
445 spin_lock_bh_nested(old_bucket_lock2, RHT_LOCK_NESTED);
446 spin_lock_bh_nested(new_bucket_lock, RHT_LOCK_NESTED2);
448 spin_lock_bh_nested(new_bucket_lock, RHT_LOCK_NESTED);
451 rcu_assign_pointer(*bucket_tail(new_tbl, new_hash),
452 tbl->buckets[new_hash]);
453 rcu_assign_pointer(*bucket_tail(new_tbl, new_hash),
454 tbl->buckets[new_hash + new_tbl->size]);
456 spin_unlock_bh(new_bucket_lock);
457 if (old_bucket_lock1 != old_bucket_lock2)
458 spin_unlock_bh(old_bucket_lock2);
459 spin_unlock_bh(old_bucket_lock1);
462 /* Publish the new, valid hash table */
463 rcu_assign_pointer(ht->tbl, new_tbl);
464 atomic_dec(&ht->shift);
466 /* Wait for readers. No new readers will have references to the
471 bucket_table_free(tbl);
475 EXPORT_SYMBOL_GPL(rhashtable_shrink);
477 static void rht_deferred_worker(struct work_struct *work)
479 struct rhashtable *ht;
480 struct bucket_table *tbl;
481 struct rhashtable_walker *walker;
483 ht = container_of(work, struct rhashtable, run_work);
484 mutex_lock(&ht->mutex);
485 if (ht->being_destroyed)
488 tbl = rht_dereference(ht->tbl, ht);
490 list_for_each_entry(walker, &ht->walkers, list)
491 walker->resize = true;
493 if (ht->p.grow_decision && ht->p.grow_decision(ht, tbl->size))
494 rhashtable_expand(ht);
495 else if (ht->p.shrink_decision && ht->p.shrink_decision(ht, tbl->size))
496 rhashtable_shrink(ht);
499 mutex_unlock(&ht->mutex);
502 static void rhashtable_wakeup_worker(struct rhashtable *ht)
504 struct bucket_table *tbl = rht_dereference_rcu(ht->tbl, ht);
505 struct bucket_table *new_tbl = rht_dereference_rcu(ht->future_tbl, ht);
506 size_t size = tbl->size;
508 /* Only adjust the table if no resizing is currently in progress. */
509 if (tbl == new_tbl &&
510 ((ht->p.grow_decision && ht->p.grow_decision(ht, size)) ||
511 (ht->p.shrink_decision && ht->p.shrink_decision(ht, size))))
512 schedule_work(&ht->run_work);
515 static void __rhashtable_insert(struct rhashtable *ht, struct rhash_head *obj,
516 struct bucket_table *tbl, u32 hash)
518 struct rhash_head *head = rht_dereference_bucket(tbl->buckets[hash],
521 if (rht_is_a_nulls(head))
522 INIT_RHT_NULLS_HEAD(obj->next, ht, hash);
524 RCU_INIT_POINTER(obj->next, head);
526 rcu_assign_pointer(tbl->buckets[hash], obj);
528 atomic_inc(&ht->nelems);
530 rhashtable_wakeup_worker(ht);
534 * rhashtable_insert - insert object into hash table
536 * @obj: pointer to hash head inside object
538 * Will take a per bucket spinlock to protect against mutual mutations
539 * on the same bucket. Multiple insertions may occur in parallel unless
540 * they map to the same bucket lock.
542 * It is safe to call this function from atomic context.
544 * Will trigger an automatic deferred table resizing if the size grows
545 * beyond the watermark indicated by grow_decision() which can be passed
546 * to rhashtable_init().
548 void rhashtable_insert(struct rhashtable *ht, struct rhash_head *obj)
550 struct bucket_table *tbl;
556 tbl = rht_dereference_rcu(ht->future_tbl, ht);
557 hash = head_hashfn(ht, tbl, obj);
558 lock = bucket_lock(tbl, hash);
561 __rhashtable_insert(ht, obj, tbl, hash);
562 spin_unlock_bh(lock);
566 EXPORT_SYMBOL_GPL(rhashtable_insert);
569 * rhashtable_remove - remove object from hash table
571 * @obj: pointer to hash head inside object
573 * Since the hash chain is single linked, the removal operation needs to
574 * walk the bucket chain upon removal. The removal operation is thus
575 * considerable slow if the hash table is not correctly sized.
577 * Will automatically shrink the table via rhashtable_expand() if the
578 * shrink_decision function specified at rhashtable_init() returns true.
580 * The caller must ensure that no concurrent table mutations occur. It is
581 * however valid to have concurrent lookups if they are RCU protected.
583 bool rhashtable_remove(struct rhashtable *ht, struct rhash_head *obj)
585 struct bucket_table *tbl;
586 struct rhash_head __rcu **pprev;
587 struct rhash_head *he;
593 tbl = rht_dereference_rcu(ht->tbl, ht);
594 hash = head_hashfn(ht, tbl, obj);
596 lock = bucket_lock(tbl, hash);
600 pprev = &tbl->buckets[hash];
601 rht_for_each(he, tbl, hash) {
607 rcu_assign_pointer(*pprev, obj->next);
613 /* The entry may be linked in either 'tbl', 'future_tbl', or both.
614 * 'future_tbl' only exists for a short period of time during
615 * resizing. Thus traversing both is fine and the added cost is
618 if (tbl != rht_dereference_rcu(ht->future_tbl, ht)) {
619 spin_unlock_bh(lock);
621 tbl = rht_dereference_rcu(ht->future_tbl, ht);
622 hash = head_hashfn(ht, tbl, obj);
624 lock = bucket_lock(tbl, hash);
629 spin_unlock_bh(lock);
632 atomic_dec(&ht->nelems);
633 rhashtable_wakeup_worker(ht);
640 EXPORT_SYMBOL_GPL(rhashtable_remove);
642 struct rhashtable_compare_arg {
643 struct rhashtable *ht;
647 static bool rhashtable_compare(void *ptr, void *arg)
649 struct rhashtable_compare_arg *x = arg;
650 struct rhashtable *ht = x->ht;
652 return !memcmp(ptr + ht->p.key_offset, x->key, ht->p.key_len);
656 * rhashtable_lookup - lookup key in hash table
658 * @key: pointer to key
660 * Computes the hash value for the key and traverses the bucket chain looking
661 * for a entry with an identical key. The first matching entry is returned.
663 * This lookup function may only be used for fixed key hash table (key_len
664 * parameter set). It will BUG() if used inappropriately.
666 * Lookups may occur in parallel with hashtable mutations and resizing.
668 void *rhashtable_lookup(struct rhashtable *ht, const void *key)
670 struct rhashtable_compare_arg arg = {
675 BUG_ON(!ht->p.key_len);
677 return rhashtable_lookup_compare(ht, key, &rhashtable_compare, &arg);
679 EXPORT_SYMBOL_GPL(rhashtable_lookup);
682 * rhashtable_lookup_compare - search hash table with compare function
684 * @key: the pointer to the key
685 * @compare: compare function, must return true on match
686 * @arg: argument passed on to compare function
688 * Traverses the bucket chain behind the provided hash value and calls the
689 * specified compare function for each entry.
691 * Lookups may occur in parallel with hashtable mutations and resizing.
693 * Returns the first entry on which the compare function returned true.
695 void *rhashtable_lookup_compare(struct rhashtable *ht, const void *key,
696 bool (*compare)(void *, void *), void *arg)
698 const struct bucket_table *tbl, *old_tbl;
699 struct rhash_head *he;
704 old_tbl = rht_dereference_rcu(ht->tbl, ht);
705 tbl = rht_dereference_rcu(ht->future_tbl, ht);
706 hash = key_hashfn(ht, key, ht->p.key_len);
708 rht_for_each_rcu(he, tbl, rht_bucket_index(tbl, hash)) {
709 if (!compare(rht_obj(ht, he), arg))
712 return rht_obj(ht, he);
715 if (unlikely(tbl != old_tbl)) {
723 EXPORT_SYMBOL_GPL(rhashtable_lookup_compare);
726 * rhashtable_lookup_insert - lookup and insert object into hash table
728 * @obj: pointer to hash head inside object
730 * Locks down the bucket chain in both the old and new table if a resize
731 * is in progress to ensure that writers can't remove from the old table
732 * and can't insert to the new table during the atomic operation of search
733 * and insertion. Searches for duplicates in both the old and new table if
734 * a resize is in progress.
736 * This lookup function may only be used for fixed key hash table (key_len
737 * parameter set). It will BUG() if used inappropriately.
739 * It is safe to call this function from atomic context.
741 * Will trigger an automatic deferred table resizing if the size grows
742 * beyond the watermark indicated by grow_decision() which can be passed
743 * to rhashtable_init().
745 bool rhashtable_lookup_insert(struct rhashtable *ht, struct rhash_head *obj)
747 struct rhashtable_compare_arg arg = {
749 .key = rht_obj(ht, obj) + ht->p.key_offset,
752 BUG_ON(!ht->p.key_len);
754 return rhashtable_lookup_compare_insert(ht, obj, &rhashtable_compare,
757 EXPORT_SYMBOL_GPL(rhashtable_lookup_insert);
760 * rhashtable_lookup_compare_insert - search and insert object to hash table
761 * with compare function
763 * @obj: pointer to hash head inside object
764 * @compare: compare function, must return true on match
765 * @arg: argument passed on to compare function
767 * Locks down the bucket chain in both the old and new table if a resize
768 * is in progress to ensure that writers can't remove from the old table
769 * and can't insert to the new table during the atomic operation of search
770 * and insertion. Searches for duplicates in both the old and new table if
771 * a resize is in progress.
773 * Lookups may occur in parallel with hashtable mutations and resizing.
775 * Will trigger an automatic deferred table resizing if the size grows
776 * beyond the watermark indicated by grow_decision() which can be passed
777 * to rhashtable_init().
779 bool rhashtable_lookup_compare_insert(struct rhashtable *ht,
780 struct rhash_head *obj,
781 bool (*compare)(void *, void *),
784 struct bucket_table *new_tbl, *old_tbl;
785 spinlock_t *new_bucket_lock, *old_bucket_lock;
786 u32 new_hash, old_hash;
789 BUG_ON(!ht->p.key_len);
793 old_tbl = rht_dereference_rcu(ht->tbl, ht);
794 old_hash = head_hashfn(ht, old_tbl, obj);
795 old_bucket_lock = bucket_lock(old_tbl, old_hash);
796 spin_lock_bh(old_bucket_lock);
798 new_tbl = rht_dereference_rcu(ht->future_tbl, ht);
799 new_hash = head_hashfn(ht, new_tbl, obj);
800 new_bucket_lock = bucket_lock(new_tbl, new_hash);
801 if (unlikely(old_tbl != new_tbl))
802 spin_lock_bh_nested(new_bucket_lock, RHT_LOCK_NESTED);
804 if (rhashtable_lookup_compare(ht, rht_obj(ht, obj) + ht->p.key_offset,
810 __rhashtable_insert(ht, obj, new_tbl, new_hash);
813 if (unlikely(old_tbl != new_tbl))
814 spin_unlock_bh(new_bucket_lock);
815 spin_unlock_bh(old_bucket_lock);
821 EXPORT_SYMBOL_GPL(rhashtable_lookup_compare_insert);
824 * rhashtable_walk_init - Initialise an iterator
825 * @ht: Table to walk over
826 * @iter: Hash table Iterator
828 * This function prepares a hash table walk.
830 * Note that if you restart a walk after rhashtable_walk_stop you
831 * may see the same object twice. Also, you may miss objects if
832 * there are removals in between rhashtable_walk_stop and the next
833 * call to rhashtable_walk_start.
835 * For a completely stable walk you should construct your own data
836 * structure outside the hash table.
838 * This function may sleep so you must not call it from interrupt
839 * context or with spin locks held.
841 * You must call rhashtable_walk_exit if this function returns
844 int rhashtable_walk_init(struct rhashtable *ht, struct rhashtable_iter *iter)
851 iter->walker = kmalloc(sizeof(*iter->walker), GFP_KERNEL);
855 mutex_lock(&ht->mutex);
856 list_add(&iter->walker->list, &ht->walkers);
857 mutex_unlock(&ht->mutex);
861 EXPORT_SYMBOL_GPL(rhashtable_walk_init);
864 * rhashtable_walk_exit - Free an iterator
865 * @iter: Hash table Iterator
867 * This function frees resources allocated by rhashtable_walk_init.
869 void rhashtable_walk_exit(struct rhashtable_iter *iter)
871 mutex_lock(&iter->ht->mutex);
872 list_del(&iter->walker->list);
873 mutex_unlock(&iter->ht->mutex);
876 EXPORT_SYMBOL_GPL(rhashtable_walk_exit);
879 * rhashtable_walk_start - Start a hash table walk
880 * @iter: Hash table iterator
882 * Start a hash table walk. Note that we take the RCU lock in all
883 * cases including when we return an error. So you must always call
884 * rhashtable_walk_stop to clean up.
886 * Returns zero if successful.
888 * Returns -EAGAIN if resize event occured. Note that the iterator
889 * will rewind back to the beginning and you may use it immediately
890 * by calling rhashtable_walk_next.
892 int rhashtable_walk_start(struct rhashtable_iter *iter)
896 if (iter->walker->resize) {
899 iter->walker->resize = false;
905 EXPORT_SYMBOL_GPL(rhashtable_walk_start);
908 * rhashtable_walk_next - Return the next object and advance the iterator
909 * @iter: Hash table iterator
911 * Note that you must call rhashtable_walk_stop when you are finished
914 * Returns the next object or NULL when the end of the table is reached.
916 * Returns -EAGAIN if resize event occured. Note that the iterator
917 * will rewind back to the beginning and you may continue to use it.
919 void *rhashtable_walk_next(struct rhashtable_iter *iter)
921 const struct bucket_table *tbl;
922 struct rhashtable *ht = iter->ht;
923 struct rhash_head *p = iter->p;
926 tbl = rht_dereference_rcu(ht->tbl, ht);
929 p = rht_dereference_bucket_rcu(p->next, tbl, iter->slot);
933 for (; iter->slot < tbl->size; iter->slot++) {
934 int skip = iter->skip;
936 rht_for_each_rcu(p, tbl, iter->slot) {
943 if (!rht_is_a_nulls(p)) {
946 obj = rht_obj(ht, p);
956 if (iter->walker->resize) {
960 iter->walker->resize = false;
961 return ERR_PTR(-EAGAIN);
966 EXPORT_SYMBOL_GPL(rhashtable_walk_next);
969 * rhashtable_walk_stop - Finish a hash table walk
970 * @iter: Hash table iterator
972 * Finish a hash table walk.
974 void rhashtable_walk_stop(struct rhashtable_iter *iter)
979 EXPORT_SYMBOL_GPL(rhashtable_walk_stop);
981 static size_t rounded_hashtable_size(struct rhashtable_params *params)
983 return max(roundup_pow_of_two(params->nelem_hint * 4 / 3),
984 1UL << params->min_shift);
988 * rhashtable_init - initialize a new hash table
989 * @ht: hash table to be initialized
990 * @params: configuration parameters
992 * Initializes a new hash table based on the provided configuration
993 * parameters. A table can be configured either with a variable or
996 * Configuration Example 1: Fixed length keys
1000 * struct rhash_head node;
1003 * struct rhashtable_params params = {
1004 * .head_offset = offsetof(struct test_obj, node),
1005 * .key_offset = offsetof(struct test_obj, key),
1006 * .key_len = sizeof(int),
1008 * .nulls_base = (1U << RHT_BASE_SHIFT),
1011 * Configuration Example 2: Variable length keys
1014 * struct rhash_head node;
1017 * u32 my_hash_fn(const void *data, u32 seed)
1019 * struct test_obj *obj = data;
1021 * return [... hash ...];
1024 * struct rhashtable_params params = {
1025 * .head_offset = offsetof(struct test_obj, node),
1027 * .obj_hashfn = my_hash_fn,
1030 int rhashtable_init(struct rhashtable *ht, struct rhashtable_params *params)
1032 struct bucket_table *tbl;
1035 size = HASH_DEFAULT_SIZE;
1037 if ((params->key_len && !params->hashfn) ||
1038 (!params->key_len && !params->obj_hashfn))
1041 if (params->nulls_base && params->nulls_base < (1U << RHT_BASE_SHIFT))
1044 params->min_shift = max_t(size_t, params->min_shift,
1045 ilog2(HASH_MIN_SIZE));
1047 if (params->nelem_hint)
1048 size = rounded_hashtable_size(params);
1050 memset(ht, 0, sizeof(*ht));
1051 mutex_init(&ht->mutex);
1052 memcpy(&ht->p, params, sizeof(*params));
1053 INIT_LIST_HEAD(&ht->walkers);
1055 if (params->locks_mul)
1056 ht->p.locks_mul = roundup_pow_of_two(params->locks_mul);
1058 ht->p.locks_mul = BUCKET_LOCKS_PER_CPU;
1060 tbl = bucket_table_alloc(ht, size);
1064 atomic_set(&ht->nelems, 0);
1065 atomic_set(&ht->shift, ilog2(tbl->size));
1066 RCU_INIT_POINTER(ht->tbl, tbl);
1067 RCU_INIT_POINTER(ht->future_tbl, tbl);
1069 if (!ht->p.hash_rnd)
1070 get_random_bytes(&ht->p.hash_rnd, sizeof(ht->p.hash_rnd));
1072 if (ht->p.grow_decision || ht->p.shrink_decision)
1073 INIT_WORK(&ht->run_work, rht_deferred_worker);
1077 EXPORT_SYMBOL_GPL(rhashtable_init);
1080 * rhashtable_destroy - destroy hash table
1081 * @ht: the hash table to destroy
1083 * Frees the bucket array. This function is not rcu safe, therefore the caller
1084 * has to make sure that no resizing may happen by unpublishing the hashtable
1085 * and waiting for the quiescent cycle before releasing the bucket array.
1087 void rhashtable_destroy(struct rhashtable *ht)
1089 ht->being_destroyed = true;
1091 if (ht->p.grow_decision || ht->p.shrink_decision)
1092 cancel_work_sync(&ht->run_work);
1094 mutex_lock(&ht->mutex);
1095 bucket_table_free(rht_dereference(ht->tbl, ht));
1096 mutex_unlock(&ht->mutex);
1098 EXPORT_SYMBOL_GPL(rhashtable_destroy);