2 * Resizable, Scalable, Concurrent Hash Table
4 * Copyright (c) 2015 Herbert Xu <herbert@gondor.apana.org.au>
5 * Copyright (c) 2014 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 #ifndef _LINUX_RHASHTABLE_H
18 #define _LINUX_RHASHTABLE_H
20 #include <linux/compiler.h>
21 #include <linux/list_nulls.h>
22 #include <linux/workqueue.h>
23 #include <linux/mutex.h>
24 #include <linux/rcupdate.h>
27 * The end of the chain is marked with a special nulls marks which has
28 * the following format:
30 * +-------+-----------------------------------------------------+-+
32 * +-------+-----------------------------------------------------+-+
34 * Base (4 bits) : Reserved to distinguish between multiple tables.
35 * Specified via &struct rhashtable_params.nulls_base.
36 * Hash (27 bits): Full hash (unmasked) of first element added to bucket
37 * 1 (1 bit) : Nulls marker (always set)
39 * The remaining bits of the next pointer remain unused for now.
41 #define RHT_BASE_BITS 4
42 #define RHT_HASH_BITS 27
43 #define RHT_BASE_SHIFT RHT_HASH_BITS
45 /* Base bits plus 1 bit for nulls marker */
46 #define RHT_HASH_RESERVED_SPACE (RHT_BASE_BITS + 1)
49 struct rhash_head __rcu *next;
53 * struct bucket_table - Table of hash buckets
54 * @size: Number of hash buckets
55 * @rehash: Current bucket being rehashed
56 * @hash_rnd: Random seed to fold into hash
57 * @locks_mask: Mask to apply before accessing locks[]
58 * @locks: Array of spinlocks protecting individual buckets
59 * @walkers: List of active walkers
60 * @rcu: RCU structure for freeing the table
61 * @future_tbl: Table under construction during rehashing
62 * @buckets: size * hash buckets
68 unsigned int locks_mask;
70 struct list_head walkers;
73 struct bucket_table __rcu *future_tbl;
75 struct rhash_head __rcu *buckets[] ____cacheline_aligned_in_smp;
79 * struct rhashtable_compare_arg - Key for the function rhashtable_compare
81 * @key: Key to compare against
83 struct rhashtable_compare_arg {
84 struct rhashtable *ht;
88 typedef u32 (*rht_hashfn_t)(const void *data, u32 len, u32 seed);
89 typedef u32 (*rht_obj_hashfn_t)(const void *data, u32 seed);
90 typedef int (*rht_obj_cmpfn_t)(struct rhashtable_compare_arg *arg,
96 * struct rhashtable_params - Hash table construction parameters
97 * @nelem_hint: Hint on number of elements, should be 75% of desired size
98 * @key_len: Length of key
99 * @key_offset: Offset of key in struct to be hashed
100 * @head_offset: Offset of rhash_head in struct to be hashed
101 * @max_size: Maximum size while expanding
102 * @min_size: Minimum size while shrinking
103 * @nulls_base: Base value to generate nulls marker
104 * @locks_mul: Number of bucket locks to allocate per cpu (default: 128)
105 * @hashfn: Function to hash key
106 * @obj_hashfn: Function to hash object
107 * @obj_cmpfn: Function to compare key with object
109 struct rhashtable_params {
114 unsigned int max_size;
115 unsigned int min_size;
119 rht_obj_hashfn_t obj_hashfn;
120 rht_obj_cmpfn_t obj_cmpfn;
124 * struct rhashtable - Hash table handle
126 * @nelems: Number of elements in table
127 * @p: Configuration parameters
128 * @run_work: Deferred worker to expand/shrink asynchronously
129 * @mutex: Mutex to protect current/future table swapping
130 * @being_destroyed: True if table is set up for destruction
133 struct bucket_table __rcu *tbl;
135 bool being_destroyed;
136 struct rhashtable_params p;
137 struct work_struct run_work;
142 * struct rhashtable_walker - Hash table walker
143 * @list: List entry on list of walkers
144 * @tbl: The table that we were walking over
146 struct rhashtable_walker {
147 struct list_head list;
148 struct bucket_table *tbl;
152 * struct rhashtable_iter - Hash table iterator, fits into netlink cb
153 * @ht: Table to iterate through
154 * @p: Current pointer
155 * @walker: Associated rhashtable walker
156 * @slot: Current slot
157 * @skip: Number of entries to skip in slot
159 struct rhashtable_iter {
160 struct rhashtable *ht;
161 struct rhash_head *p;
162 struct rhashtable_walker *walker;
167 static inline unsigned long rht_marker(const struct rhashtable *ht, u32 hash)
169 return NULLS_MARKER(ht->p.nulls_base + hash);
172 #define INIT_RHT_NULLS_HEAD(ptr, ht, hash) \
173 ((ptr) = (typeof(ptr)) rht_marker(ht, hash))
175 static inline bool rht_is_a_nulls(const struct rhash_head *ptr)
177 return ((unsigned long) ptr & 1);
180 static inline unsigned long rht_get_nulls_value(const struct rhash_head *ptr)
182 return ((unsigned long) ptr) >> 1;
185 static inline void *rht_obj(const struct rhashtable *ht,
186 const struct rhash_head *he)
188 return (char *)he - ht->p.head_offset;
191 static inline unsigned int rht_bucket_index(const struct bucket_table *tbl,
194 return (hash >> RHT_HASH_RESERVED_SPACE) & (tbl->size - 1);
197 static inline unsigned int rht_key_hashfn(
198 struct rhashtable *ht, const struct bucket_table *tbl,
199 const void *key, const struct rhashtable_params params)
201 return rht_bucket_index(tbl, params.hashfn(key, params.key_len ?:
206 static inline unsigned int rht_head_hashfn(
207 struct rhashtable *ht, const struct bucket_table *tbl,
208 const struct rhash_head *he, const struct rhashtable_params params)
210 const char *ptr = rht_obj(ht, he);
212 return likely(params.obj_hashfn) ?
213 rht_bucket_index(tbl, params.obj_hashfn(ptr, tbl->hash_rnd)) :
214 rht_key_hashfn(ht, tbl, ptr + params.key_offset, params);
218 * rht_grow_above_75 - returns true if nelems > 0.75 * table-size
220 * @tbl: current table
222 static inline bool rht_grow_above_75(const struct rhashtable *ht,
223 const struct bucket_table *tbl)
225 /* Expand table when exceeding 75% load */
226 return atomic_read(&ht->nelems) > (tbl->size / 4 * 3) &&
227 (!ht->p.max_size || tbl->size < ht->p.max_size);
231 * rht_shrink_below_30 - returns true if nelems < 0.3 * table-size
233 * @tbl: current table
235 static inline bool rht_shrink_below_30(const struct rhashtable *ht,
236 const struct bucket_table *tbl)
238 /* Shrink table beneath 30% load */
239 return atomic_read(&ht->nelems) < (tbl->size * 3 / 10) &&
240 tbl->size > ht->p.min_size;
243 /* The bucket lock is selected based on the hash and protects mutations
244 * on a group of hash buckets.
246 * A maximum of tbl->size/2 bucket locks is allocated. This ensures that
247 * a single lock always covers both buckets which may both contains
248 * entries which link to the same bucket of the old table during resizing.
249 * This allows to simplify the locking as locking the bucket in both
250 * tables during resize always guarantee protection.
252 * IMPORTANT: When holding the bucket lock of both the old and new table
253 * during expansions and shrinking, the old bucket lock must always be
256 static inline spinlock_t *rht_bucket_lock(const struct bucket_table *tbl,
259 return &tbl->locks[hash & tbl->locks_mask];
262 #ifdef CONFIG_PROVE_LOCKING
263 int lockdep_rht_mutex_is_held(struct rhashtable *ht);
264 int lockdep_rht_bucket_is_held(const struct bucket_table *tbl, u32 hash);
266 static inline int lockdep_rht_mutex_is_held(struct rhashtable *ht)
271 static inline int lockdep_rht_bucket_is_held(const struct bucket_table *tbl,
276 #endif /* CONFIG_PROVE_LOCKING */
278 int rhashtable_init(struct rhashtable *ht,
279 const struct rhashtable_params *params);
281 int rhashtable_insert_slow(struct rhashtable *ht, const void *key,
282 struct rhash_head *obj,
283 struct bucket_table *old_tbl);
285 int rhashtable_expand(struct rhashtable *ht);
286 int rhashtable_shrink(struct rhashtable *ht);
288 int rhashtable_walk_init(struct rhashtable *ht, struct rhashtable_iter *iter);
289 void rhashtable_walk_exit(struct rhashtable_iter *iter);
290 int rhashtable_walk_start(struct rhashtable_iter *iter) __acquires(RCU);
291 void *rhashtable_walk_next(struct rhashtable_iter *iter);
292 void rhashtable_walk_stop(struct rhashtable_iter *iter) __releases(RCU);
294 void rhashtable_destroy(struct rhashtable *ht);
296 #define rht_dereference(p, ht) \
297 rcu_dereference_protected(p, lockdep_rht_mutex_is_held(ht))
299 #define rht_dereference_rcu(p, ht) \
300 rcu_dereference_check(p, lockdep_rht_mutex_is_held(ht))
302 #define rht_dereference_bucket(p, tbl, hash) \
303 rcu_dereference_protected(p, lockdep_rht_bucket_is_held(tbl, hash))
305 #define rht_dereference_bucket_rcu(p, tbl, hash) \
306 rcu_dereference_check(p, lockdep_rht_bucket_is_held(tbl, hash))
308 #define rht_entry(tpos, pos, member) \
309 ({ tpos = container_of(pos, typeof(*tpos), member); 1; })
312 * rht_for_each_continue - continue iterating over hash chain
313 * @pos: the &struct rhash_head to use as a loop cursor.
314 * @head: the previous &struct rhash_head to continue from
315 * @tbl: the &struct bucket_table
316 * @hash: the hash value / bucket index
318 #define rht_for_each_continue(pos, head, tbl, hash) \
319 for (pos = rht_dereference_bucket(head, tbl, hash); \
320 !rht_is_a_nulls(pos); \
321 pos = rht_dereference_bucket((pos)->next, tbl, hash))
324 * rht_for_each - iterate over hash chain
325 * @pos: the &struct rhash_head to use as a loop cursor.
326 * @tbl: the &struct bucket_table
327 * @hash: the hash value / bucket index
329 #define rht_for_each(pos, tbl, hash) \
330 rht_for_each_continue(pos, (tbl)->buckets[hash], tbl, hash)
333 * rht_for_each_entry_continue - continue iterating over hash chain
334 * @tpos: the type * to use as a loop cursor.
335 * @pos: the &struct rhash_head to use as a loop cursor.
336 * @head: the previous &struct rhash_head to continue from
337 * @tbl: the &struct bucket_table
338 * @hash: the hash value / bucket index
339 * @member: name of the &struct rhash_head within the hashable struct.
341 #define rht_for_each_entry_continue(tpos, pos, head, tbl, hash, member) \
342 for (pos = rht_dereference_bucket(head, tbl, hash); \
343 (!rht_is_a_nulls(pos)) && rht_entry(tpos, pos, member); \
344 pos = rht_dereference_bucket((pos)->next, tbl, hash))
347 * rht_for_each_entry - iterate over hash chain of given type
348 * @tpos: the type * to use as a loop cursor.
349 * @pos: the &struct rhash_head to use as a loop cursor.
350 * @tbl: the &struct bucket_table
351 * @hash: the hash value / bucket index
352 * @member: name of the &struct rhash_head within the hashable struct.
354 #define rht_for_each_entry(tpos, pos, tbl, hash, member) \
355 rht_for_each_entry_continue(tpos, pos, (tbl)->buckets[hash], \
359 * rht_for_each_entry_safe - safely iterate over hash chain of given type
360 * @tpos: the type * to use as a loop cursor.
361 * @pos: the &struct rhash_head to use as a loop cursor.
362 * @next: the &struct rhash_head to use as next in loop cursor.
363 * @tbl: the &struct bucket_table
364 * @hash: the hash value / bucket index
365 * @member: name of the &struct rhash_head within the hashable struct.
367 * This hash chain list-traversal primitive allows for the looped code to
368 * remove the loop cursor from the list.
370 #define rht_for_each_entry_safe(tpos, pos, next, tbl, hash, member) \
371 for (pos = rht_dereference_bucket((tbl)->buckets[hash], tbl, hash), \
372 next = !rht_is_a_nulls(pos) ? \
373 rht_dereference_bucket(pos->next, tbl, hash) : NULL; \
374 (!rht_is_a_nulls(pos)) && rht_entry(tpos, pos, member); \
376 next = !rht_is_a_nulls(pos) ? \
377 rht_dereference_bucket(pos->next, tbl, hash) : NULL)
380 * rht_for_each_rcu_continue - continue iterating over rcu hash chain
381 * @pos: the &struct rhash_head to use as a loop cursor.
382 * @head: the previous &struct rhash_head to continue from
383 * @tbl: the &struct bucket_table
384 * @hash: the hash value / bucket index
386 * This hash chain list-traversal primitive may safely run concurrently with
387 * the _rcu mutation primitives such as rhashtable_insert() as long as the
388 * traversal is guarded by rcu_read_lock().
390 #define rht_for_each_rcu_continue(pos, head, tbl, hash) \
391 for (({barrier(); }), \
392 pos = rht_dereference_bucket_rcu(head, tbl, hash); \
393 !rht_is_a_nulls(pos); \
394 pos = rcu_dereference_raw(pos->next))
397 * rht_for_each_rcu - iterate over rcu hash chain
398 * @pos: the &struct rhash_head to use as a loop cursor.
399 * @tbl: the &struct bucket_table
400 * @hash: the hash value / bucket index
402 * This hash chain list-traversal primitive may safely run concurrently with
403 * the _rcu mutation primitives such as rhashtable_insert() as long as the
404 * traversal is guarded by rcu_read_lock().
406 #define rht_for_each_rcu(pos, tbl, hash) \
407 rht_for_each_rcu_continue(pos, (tbl)->buckets[hash], tbl, hash)
410 * rht_for_each_entry_rcu_continue - continue iterating over rcu hash chain
411 * @tpos: the type * to use as a loop cursor.
412 * @pos: the &struct rhash_head to use as a loop cursor.
413 * @head: the previous &struct rhash_head to continue from
414 * @tbl: the &struct bucket_table
415 * @hash: the hash value / bucket index
416 * @member: name of the &struct rhash_head within the hashable struct.
418 * This hash chain list-traversal primitive may safely run concurrently with
419 * the _rcu mutation primitives such as rhashtable_insert() as long as the
420 * traversal is guarded by rcu_read_lock().
422 #define rht_for_each_entry_rcu_continue(tpos, pos, head, tbl, hash, member) \
423 for (({barrier(); }), \
424 pos = rht_dereference_bucket_rcu(head, tbl, hash); \
425 (!rht_is_a_nulls(pos)) && rht_entry(tpos, pos, member); \
426 pos = rht_dereference_bucket_rcu(pos->next, tbl, hash))
429 * rht_for_each_entry_rcu - iterate over rcu hash chain of given type
430 * @tpos: the type * to use as a loop cursor.
431 * @pos: the &struct rhash_head to use as a loop cursor.
432 * @tbl: the &struct bucket_table
433 * @hash: the hash value / bucket index
434 * @member: name of the &struct rhash_head within the hashable struct.
436 * This hash chain list-traversal primitive may safely run concurrently with
437 * the _rcu mutation primitives such as rhashtable_insert() as long as the
438 * traversal is guarded by rcu_read_lock().
440 #define rht_for_each_entry_rcu(tpos, pos, tbl, hash, member) \
441 rht_for_each_entry_rcu_continue(tpos, pos, (tbl)->buckets[hash],\
444 static inline int rhashtable_compare(struct rhashtable_compare_arg *arg,
447 struct rhashtable *ht = arg->ht;
448 const char *ptr = obj;
450 return memcmp(ptr + ht->p.key_offset, arg->key, ht->p.key_len);
454 * rhashtable_lookup_fast - search hash table, inlined version
456 * @key: the pointer to the key
457 * @params: hash table parameters
459 * Computes the hash value for the key and traverses the bucket chain looking
460 * for a entry with an identical key. The first matching entry is returned.
462 * Returns the first entry on which the compare function returned true.
464 static inline void *rhashtable_lookup_fast(
465 struct rhashtable *ht, const void *key,
466 const struct rhashtable_params params)
468 struct rhashtable_compare_arg arg = {
472 const struct bucket_table *tbl;
473 struct rhash_head *he;
478 tbl = rht_dereference_rcu(ht->tbl, ht);
480 hash = rht_key_hashfn(ht, tbl, key, params);
481 rht_for_each_rcu(he, tbl, hash) {
482 if (params.obj_cmpfn ?
483 params.obj_cmpfn(&arg, rht_obj(ht, he)) :
484 rhashtable_compare(&arg, rht_obj(ht, he)))
487 return rht_obj(ht, he);
490 /* Ensure we see any new tables. */
493 tbl = rht_dereference_rcu(tbl->future_tbl, ht);
501 static inline int __rhashtable_insert_fast(
502 struct rhashtable *ht, const void *key, struct rhash_head *obj,
503 const struct rhashtable_params params)
505 struct rhashtable_compare_arg arg = {
510 struct bucket_table *tbl, *new_tbl;
511 struct rhash_head *head;
517 tbl = rht_dereference_rcu(ht->tbl, ht);
518 hash = rht_head_hashfn(ht, tbl, obj, params);
519 lock = rht_bucket_lock(tbl, hash);
523 /* Because we have already taken the bucket lock in tbl,
524 * if we find that future_tbl is not yet visible then
525 * that guarantees all other insertions of the same entry
526 * will also grab the bucket lock in tbl because until
527 * the rehash completes ht->tbl won't be changed.
529 new_tbl = rht_dereference_rcu(tbl->future_tbl, ht);
530 if (unlikely(new_tbl)) {
531 err = rhashtable_insert_slow(ht, key, obj, new_tbl);
538 rht_for_each(head, tbl, hash) {
539 if (unlikely(!(params.obj_cmpfn ?
540 params.obj_cmpfn(&arg, rht_obj(ht, head)) :
541 rhashtable_compare(&arg, rht_obj(ht, head)))))
548 head = rht_dereference_bucket(tbl->buckets[hash], tbl, hash);
550 RCU_INIT_POINTER(obj->next, head);
552 rcu_assign_pointer(tbl->buckets[hash], obj);
554 atomic_inc(&ht->nelems);
555 if (rht_grow_above_75(ht, tbl))
556 schedule_work(&ht->run_work);
559 spin_unlock_bh(lock);
566 * rhashtable_insert_fast - insert object into hash table
568 * @obj: pointer to hash head inside object
569 * @params: hash table parameters
571 * Will take a per bucket spinlock to protect against mutual mutations
572 * on the same bucket. Multiple insertions may occur in parallel unless
573 * they map to the same bucket lock.
575 * It is safe to call this function from atomic context.
577 * Will trigger an automatic deferred table resizing if the size grows
578 * beyond the watermark indicated by grow_decision() which can be passed
579 * to rhashtable_init().
581 static inline int rhashtable_insert_fast(
582 struct rhashtable *ht, struct rhash_head *obj,
583 const struct rhashtable_params params)
585 return __rhashtable_insert_fast(ht, NULL, obj, params);
589 * rhashtable_lookup_insert_fast - lookup and insert object into hash table
591 * @obj: pointer to hash head inside object
592 * @params: hash table parameters
594 * Locks down the bucket chain in both the old and new table if a resize
595 * is in progress to ensure that writers can't remove from the old table
596 * and can't insert to the new table during the atomic operation of search
597 * and insertion. Searches for duplicates in both the old and new table if
598 * a resize is in progress.
600 * This lookup function may only be used for fixed key hash table (key_len
601 * parameter set). It will BUG() if used inappropriately.
603 * It is safe to call this function from atomic context.
605 * Will trigger an automatic deferred table resizing if the size grows
606 * beyond the watermark indicated by grow_decision() which can be passed
607 * to rhashtable_init().
609 static inline int rhashtable_lookup_insert_fast(
610 struct rhashtable *ht, struct rhash_head *obj,
611 const struct rhashtable_params params)
613 const char *key = rht_obj(ht, obj);
615 BUG_ON(ht->p.obj_hashfn);
617 return __rhashtable_insert_fast(ht, key + ht->p.key_offset, obj,
622 * rhashtable_lookup_insert_key - search and insert object to hash table
626 * @obj: pointer to hash head inside object
627 * @params: hash table parameters
629 * Locks down the bucket chain in both the old and new table if a resize
630 * is in progress to ensure that writers can't remove from the old table
631 * and can't insert to the new table during the atomic operation of search
632 * and insertion. Searches for duplicates in both the old and new table if
633 * a resize is in progress.
635 * Lookups may occur in parallel with hashtable mutations and resizing.
637 * Will trigger an automatic deferred table resizing if the size grows
638 * beyond the watermark indicated by grow_decision() which can be passed
639 * to rhashtable_init().
641 * Returns zero on success.
643 static inline int rhashtable_lookup_insert_key(
644 struct rhashtable *ht, const void *key, struct rhash_head *obj,
645 const struct rhashtable_params params)
647 BUG_ON(!ht->p.obj_hashfn || !key);
649 return __rhashtable_insert_fast(ht, key, obj, params);
652 static inline int __rhashtable_remove_fast(
653 struct rhashtable *ht, struct bucket_table *tbl,
654 struct rhash_head *obj, const struct rhashtable_params params)
656 struct rhash_head __rcu **pprev;
657 struct rhash_head *he;
662 hash = rht_head_hashfn(ht, tbl, obj, params);
663 lock = rht_bucket_lock(tbl, hash);
667 pprev = &tbl->buckets[hash];
668 rht_for_each(he, tbl, hash) {
674 rcu_assign_pointer(*pprev, obj->next);
679 spin_unlock_bh(lock);
685 * rhashtable_remove_fast - remove object from hash table
687 * @obj: pointer to hash head inside object
688 * @params: hash table parameters
690 * Since the hash chain is single linked, the removal operation needs to
691 * walk the bucket chain upon removal. The removal operation is thus
692 * considerable slow if the hash table is not correctly sized.
694 * Will automatically shrink the table via rhashtable_expand() if the
695 * shrink_decision function specified at rhashtable_init() returns true.
697 * Returns zero on success, -ENOENT if the entry could not be found.
699 static inline int rhashtable_remove_fast(
700 struct rhashtable *ht, struct rhash_head *obj,
701 const struct rhashtable_params params)
703 struct bucket_table *tbl;
708 tbl = rht_dereference_rcu(ht->tbl, ht);
710 /* Because we have already taken (and released) the bucket
711 * lock in old_tbl, if we find that future_tbl is not yet
712 * visible then that guarantees the entry to still be in
713 * the old tbl if it exists.
715 while ((err = __rhashtable_remove_fast(ht, tbl, obj, params)) &&
716 (tbl = rht_dereference_rcu(tbl->future_tbl, ht)))
722 atomic_dec(&ht->nelems);
723 if (rht_shrink_below_30(ht, tbl))
724 schedule_work(&ht->run_work);
732 #endif /* _LINUX_RHASHTABLE_H */