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/kernel.h>
18 #include <linux/init.h>
19 #include <linux/log2.h>
20 #include <linux/sched.h>
21 #include <linux/slab.h>
22 #include <linux/vmalloc.h>
24 #include <linux/jhash.h>
25 #include <linux/random.h>
26 #include <linux/rhashtable.h>
27 #include <linux/err.h>
29 #define HASH_DEFAULT_SIZE 64UL
30 #define HASH_MIN_SIZE 4U
31 #define BUCKET_LOCKS_PER_CPU 128UL
33 static u32 head_hashfn(struct rhashtable *ht,
34 const struct bucket_table *tbl,
35 const struct rhash_head *he)
37 return rht_head_hashfn(ht, tbl, he, ht->p);
40 #ifdef CONFIG_PROVE_LOCKING
41 #define ASSERT_RHT_MUTEX(HT) BUG_ON(!lockdep_rht_mutex_is_held(HT))
43 int lockdep_rht_mutex_is_held(struct rhashtable *ht)
45 return (debug_locks) ? lockdep_is_held(&ht->mutex) : 1;
47 EXPORT_SYMBOL_GPL(lockdep_rht_mutex_is_held);
49 int lockdep_rht_bucket_is_held(const struct bucket_table *tbl, u32 hash)
51 spinlock_t *lock = rht_bucket_lock(tbl, hash);
53 return (debug_locks) ? lockdep_is_held(lock) : 1;
55 EXPORT_SYMBOL_GPL(lockdep_rht_bucket_is_held);
57 #define ASSERT_RHT_MUTEX(HT)
61 static int alloc_bucket_locks(struct rhashtable *ht, struct bucket_table *tbl)
64 #if defined(CONFIG_PROVE_LOCKING)
65 unsigned int nr_pcpus = 2;
67 unsigned int nr_pcpus = num_possible_cpus();
70 nr_pcpus = min_t(unsigned int, nr_pcpus, 32UL);
71 size = roundup_pow_of_two(nr_pcpus * ht->p.locks_mul);
73 /* Never allocate more than 0.5 locks per bucket */
74 size = min_t(unsigned int, size, tbl->size >> 1);
76 if (sizeof(spinlock_t) != 0) {
78 if (size * sizeof(spinlock_t) > PAGE_SIZE)
79 tbl->locks = vmalloc(size * sizeof(spinlock_t));
82 tbl->locks = kmalloc_array(size, sizeof(spinlock_t),
86 for (i = 0; i < size; i++)
87 spin_lock_init(&tbl->locks[i]);
89 tbl->locks_mask = size - 1;
94 static void bucket_table_free(const struct bucket_table *tbl)
102 static void bucket_table_free_rcu(struct rcu_head *head)
104 bucket_table_free(container_of(head, struct bucket_table, rcu));
107 static struct bucket_table *bucket_table_alloc(struct rhashtable *ht,
110 struct bucket_table *tbl = NULL;
114 size = sizeof(*tbl) + nbuckets * sizeof(tbl->buckets[0]);
115 if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER))
116 tbl = kzalloc(size, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY);
122 tbl->size = nbuckets;
124 if (alloc_bucket_locks(ht, tbl) < 0) {
125 bucket_table_free(tbl);
129 INIT_LIST_HEAD(&tbl->walkers);
131 get_random_bytes(&tbl->hash_rnd, sizeof(tbl->hash_rnd));
133 for (i = 0; i < nbuckets; i++)
134 INIT_RHT_NULLS_HEAD(tbl->buckets[i], ht, i);
139 static int rhashtable_rehash_one(struct rhashtable *ht, unsigned old_hash)
141 struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht);
142 struct bucket_table *new_tbl =
143 rht_dereference(old_tbl->future_tbl, ht) ?: old_tbl;
144 struct rhash_head __rcu **pprev = &old_tbl->buckets[old_hash];
146 struct rhash_head *head, *next, *entry;
147 spinlock_t *new_bucket_lock;
150 rht_for_each(entry, old_tbl, old_hash) {
152 next = rht_dereference_bucket(entry->next, old_tbl, old_hash);
154 if (rht_is_a_nulls(next))
157 pprev = &entry->next;
163 new_hash = head_hashfn(ht, new_tbl, entry);
165 new_bucket_lock = rht_bucket_lock(new_tbl, new_hash);
167 spin_lock_nested(new_bucket_lock, SINGLE_DEPTH_NESTING);
168 head = rht_dereference_bucket(new_tbl->buckets[new_hash],
171 if (rht_is_a_nulls(head))
172 INIT_RHT_NULLS_HEAD(entry->next, ht, new_hash);
174 RCU_INIT_POINTER(entry->next, head);
176 rcu_assign_pointer(new_tbl->buckets[new_hash], entry);
177 spin_unlock(new_bucket_lock);
179 rcu_assign_pointer(*pprev, next);
185 static void rhashtable_rehash_chain(struct rhashtable *ht, unsigned old_hash)
187 struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht);
188 spinlock_t *old_bucket_lock;
190 old_bucket_lock = rht_bucket_lock(old_tbl, old_hash);
192 spin_lock_bh(old_bucket_lock);
193 while (!rhashtable_rehash_one(ht, old_hash))
196 spin_unlock_bh(old_bucket_lock);
199 static void rhashtable_rehash(struct rhashtable *ht,
200 struct bucket_table *new_tbl)
202 struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht);
203 struct rhashtable_walker *walker;
206 /* Make insertions go into the new, empty table right away. Deletions
207 * and lookups will be attempted in both tables until we synchronize.
209 rcu_assign_pointer(old_tbl->future_tbl, new_tbl);
211 /* Ensure the new table is visible to readers. */
214 for (old_hash = 0; old_hash < old_tbl->size; old_hash++)
215 rhashtable_rehash_chain(ht, old_hash);
217 /* Publish the new table pointer. */
218 rcu_assign_pointer(ht->tbl, new_tbl);
220 list_for_each_entry(walker, &old_tbl->walkers, list)
223 /* Wait for readers. All new readers will see the new
224 * table, and thus no references to the old table will
227 call_rcu(&old_tbl->rcu, bucket_table_free_rcu);
231 * rhashtable_expand - Expand hash table while allowing concurrent lookups
232 * @ht: the hash table to expand
234 * A secondary bucket array is allocated and the hash entries are migrated.
236 * This function may only be called in a context where it is safe to call
237 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
239 * The caller must ensure that no concurrent resizing occurs by holding
242 * It is valid to have concurrent insertions and deletions protected by per
243 * bucket locks or concurrent RCU protected lookups and traversals.
245 int rhashtable_expand(struct rhashtable *ht)
247 struct bucket_table *new_tbl, *old_tbl = rht_dereference(ht->tbl, ht);
249 ASSERT_RHT_MUTEX(ht);
251 new_tbl = bucket_table_alloc(ht, old_tbl->size * 2);
255 rhashtable_rehash(ht, new_tbl);
258 EXPORT_SYMBOL_GPL(rhashtable_expand);
261 * rhashtable_shrink - Shrink hash table while allowing concurrent lookups
262 * @ht: the hash table to shrink
264 * This function may only be called in a context where it is safe to call
265 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
267 * The caller must ensure that no concurrent resizing occurs by holding
270 * The caller must ensure that no concurrent table mutations take place.
271 * It is however valid to have concurrent lookups if they are RCU protected.
273 * It is valid to have concurrent insertions and deletions protected by per
274 * bucket locks or concurrent RCU protected lookups and traversals.
276 int rhashtable_shrink(struct rhashtable *ht)
278 struct bucket_table *new_tbl, *old_tbl = rht_dereference(ht->tbl, ht);
280 ASSERT_RHT_MUTEX(ht);
282 new_tbl = bucket_table_alloc(ht, old_tbl->size / 2);
286 rhashtable_rehash(ht, new_tbl);
289 EXPORT_SYMBOL_GPL(rhashtable_shrink);
291 static void rht_deferred_worker(struct work_struct *work)
293 struct rhashtable *ht;
294 struct bucket_table *tbl;
296 ht = container_of(work, struct rhashtable, run_work);
297 mutex_lock(&ht->mutex);
298 if (ht->being_destroyed)
301 tbl = rht_dereference(ht->tbl, ht);
303 if (rht_grow_above_75(ht, tbl))
304 rhashtable_expand(ht);
305 else if (rht_shrink_below_30(ht, tbl))
306 rhashtable_shrink(ht);
308 mutex_unlock(&ht->mutex);
311 int rhashtable_insert_slow(struct rhashtable *ht, const void *key,
312 struct rhash_head *obj,
313 struct bucket_table *tbl)
315 struct rhash_head *head;
319 hash = head_hashfn(ht, tbl, obj);
320 spin_lock_nested(rht_bucket_lock(tbl, hash), SINGLE_DEPTH_NESTING);
322 if (key && rhashtable_lookup_fast(ht, key, ht->p))
327 head = rht_dereference_bucket(tbl->buckets[hash], tbl, hash);
329 RCU_INIT_POINTER(obj->next, head);
331 rcu_assign_pointer(tbl->buckets[hash], obj);
333 atomic_inc(&ht->nelems);
336 spin_unlock(rht_bucket_lock(tbl, hash));
340 EXPORT_SYMBOL_GPL(rhashtable_insert_slow);
343 * rhashtable_walk_init - Initialise an iterator
344 * @ht: Table to walk over
345 * @iter: Hash table Iterator
347 * This function prepares a hash table walk.
349 * Note that if you restart a walk after rhashtable_walk_stop you
350 * may see the same object twice. Also, you may miss objects if
351 * there are removals in between rhashtable_walk_stop and the next
352 * call to rhashtable_walk_start.
354 * For a completely stable walk you should construct your own data
355 * structure outside the hash table.
357 * This function may sleep so you must not call it from interrupt
358 * context or with spin locks held.
360 * You must call rhashtable_walk_exit if this function returns
363 int rhashtable_walk_init(struct rhashtable *ht, struct rhashtable_iter *iter)
370 iter->walker = kmalloc(sizeof(*iter->walker), GFP_KERNEL);
374 mutex_lock(&ht->mutex);
375 iter->walker->tbl = rht_dereference(ht->tbl, ht);
376 list_add(&iter->walker->list, &iter->walker->tbl->walkers);
377 mutex_unlock(&ht->mutex);
381 EXPORT_SYMBOL_GPL(rhashtable_walk_init);
384 * rhashtable_walk_exit - Free an iterator
385 * @iter: Hash table Iterator
387 * This function frees resources allocated by rhashtable_walk_init.
389 void rhashtable_walk_exit(struct rhashtable_iter *iter)
391 mutex_lock(&iter->ht->mutex);
392 if (iter->walker->tbl)
393 list_del(&iter->walker->list);
394 mutex_unlock(&iter->ht->mutex);
397 EXPORT_SYMBOL_GPL(rhashtable_walk_exit);
400 * rhashtable_walk_start - Start a hash table walk
401 * @iter: Hash table iterator
403 * Start a hash table walk. Note that we take the RCU lock in all
404 * cases including when we return an error. So you must always call
405 * rhashtable_walk_stop to clean up.
407 * Returns zero if successful.
409 * Returns -EAGAIN if resize event occured. Note that the iterator
410 * will rewind back to the beginning and you may use it immediately
411 * by calling rhashtable_walk_next.
413 int rhashtable_walk_start(struct rhashtable_iter *iter)
416 struct rhashtable *ht = iter->ht;
418 mutex_lock(&ht->mutex);
420 if (iter->walker->tbl)
421 list_del(&iter->walker->list);
425 mutex_unlock(&ht->mutex);
427 if (!iter->walker->tbl) {
428 iter->walker->tbl = rht_dereference_rcu(ht->tbl, ht);
434 EXPORT_SYMBOL_GPL(rhashtable_walk_start);
437 * rhashtable_walk_next - Return the next object and advance the iterator
438 * @iter: Hash table iterator
440 * Note that you must call rhashtable_walk_stop when you are finished
443 * Returns the next object or NULL when the end of the table is reached.
445 * Returns -EAGAIN if resize event occured. Note that the iterator
446 * will rewind back to the beginning and you may continue to use it.
448 void *rhashtable_walk_next(struct rhashtable_iter *iter)
450 struct bucket_table *tbl = iter->walker->tbl;
451 struct rhashtable *ht = iter->ht;
452 struct rhash_head *p = iter->p;
456 p = rht_dereference_bucket_rcu(p->next, tbl, iter->slot);
460 for (; iter->slot < tbl->size; iter->slot++) {
461 int skip = iter->skip;
463 rht_for_each_rcu(p, tbl, iter->slot) {
470 if (!rht_is_a_nulls(p)) {
473 obj = rht_obj(ht, p);
480 /* Ensure we see any new tables. */
483 iter->walker->tbl = rht_dereference_rcu(tbl->future_tbl, ht);
484 if (iter->walker->tbl) {
487 return ERR_PTR(-EAGAIN);
496 EXPORT_SYMBOL_GPL(rhashtable_walk_next);
499 * rhashtable_walk_stop - Finish a hash table walk
500 * @iter: Hash table iterator
502 * Finish a hash table walk.
504 void rhashtable_walk_stop(struct rhashtable_iter *iter)
507 struct rhashtable *ht;
508 struct bucket_table *tbl = iter->walker->tbl;
515 mutex_lock(&ht->mutex);
516 if (tbl->rehash < tbl->size)
517 list_add(&iter->walker->list, &tbl->walkers);
519 iter->walker->tbl = NULL;
520 mutex_unlock(&ht->mutex);
527 EXPORT_SYMBOL_GPL(rhashtable_walk_stop);
529 static size_t rounded_hashtable_size(const struct rhashtable_params *params)
531 return max(roundup_pow_of_two(params->nelem_hint * 4 / 3),
532 (unsigned long)params->min_size);
536 * rhashtable_init - initialize a new hash table
537 * @ht: hash table to be initialized
538 * @params: configuration parameters
540 * Initializes a new hash table based on the provided configuration
541 * parameters. A table can be configured either with a variable or
544 * Configuration Example 1: Fixed length keys
548 * struct rhash_head node;
551 * struct rhashtable_params params = {
552 * .head_offset = offsetof(struct test_obj, node),
553 * .key_offset = offsetof(struct test_obj, key),
554 * .key_len = sizeof(int),
556 * .nulls_base = (1U << RHT_BASE_SHIFT),
559 * Configuration Example 2: Variable length keys
562 * struct rhash_head node;
565 * u32 my_hash_fn(const void *data, u32 seed)
567 * struct test_obj *obj = data;
569 * return [... hash ...];
572 * struct rhashtable_params params = {
573 * .head_offset = offsetof(struct test_obj, node),
575 * .obj_hashfn = my_hash_fn,
578 int rhashtable_init(struct rhashtable *ht,
579 const struct rhashtable_params *params)
581 struct bucket_table *tbl;
584 size = HASH_DEFAULT_SIZE;
586 if ((!(params->key_len && params->hashfn) && !params->obj_hashfn) ||
587 (params->obj_hashfn && !params->obj_cmpfn))
590 if (params->nulls_base && params->nulls_base < (1U << RHT_BASE_SHIFT))
593 if (params->nelem_hint)
594 size = rounded_hashtable_size(params);
596 memset(ht, 0, sizeof(*ht));
597 mutex_init(&ht->mutex);
598 memcpy(&ht->p, params, sizeof(*params));
600 if (params->min_size)
601 ht->p.min_size = roundup_pow_of_two(params->min_size);
603 if (params->max_size)
604 ht->p.max_size = rounddown_pow_of_two(params->max_size);
606 ht->p.min_size = max(ht->p.min_size, HASH_MIN_SIZE);
608 if (params->locks_mul)
609 ht->p.locks_mul = roundup_pow_of_two(params->locks_mul);
611 ht->p.locks_mul = BUCKET_LOCKS_PER_CPU;
613 tbl = bucket_table_alloc(ht, size);
617 atomic_set(&ht->nelems, 0);
619 RCU_INIT_POINTER(ht->tbl, tbl);
621 INIT_WORK(&ht->run_work, rht_deferred_worker);
625 EXPORT_SYMBOL_GPL(rhashtable_init);
628 * rhashtable_destroy - destroy hash table
629 * @ht: the hash table to destroy
631 * Frees the bucket array. This function is not rcu safe, therefore the caller
632 * has to make sure that no resizing may happen by unpublishing the hashtable
633 * and waiting for the quiescent cycle before releasing the bucket array.
635 void rhashtable_destroy(struct rhashtable *ht)
637 ht->being_destroyed = true;
639 cancel_work_sync(&ht->run_work);
641 mutex_lock(&ht->mutex);
642 bucket_table_free(rht_dereference(ht->tbl, ht));
643 mutex_unlock(&ht->mutex);
645 EXPORT_SYMBOL_GPL(rhashtable_destroy);