rhashtable: Use SINGLE_DEPTH_NESTING
[linux-2.6-block.git] / lib / rhashtable.c
CommitLineData
7e1e7763
TG
1/*
2 * Resizable, Scalable, Concurrent Hash Table
3 *
a5ec68e3 4 * Copyright (c) 2014-2015 Thomas Graf <tgraf@suug.ch>
7e1e7763
TG
5 * Copyright (c) 2008-2014 Patrick McHardy <kaber@trash.net>
6 *
7 * Based on the following paper:
8 * https://www.usenix.org/legacy/event/atc11/tech/final_files/Triplett.pdf
9 *
10 * Code partially derived from nft_hash
11 *
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.
15 */
16
17#include <linux/kernel.h>
18#include <linux/init.h>
19#include <linux/log2.h>
5beb5c90 20#include <linux/sched.h>
7e1e7763
TG
21#include <linux/slab.h>
22#include <linux/vmalloc.h>
23#include <linux/mm.h>
87545899 24#include <linux/jhash.h>
7e1e7763
TG
25#include <linux/random.h>
26#include <linux/rhashtable.h>
61d7b097 27#include <linux/err.h>
7e1e7763
TG
28
29#define HASH_DEFAULT_SIZE 64UL
30#define HASH_MIN_SIZE 4UL
97defe1e
TG
31#define BUCKET_LOCKS_PER_CPU 128UL
32
f89bd6f8
TG
33/* Base bits plus 1 bit for nulls marker */
34#define HASH_RESERVED_SPACE (RHT_BASE_BITS + 1)
35
97defe1e
TG
36/* The bucket lock is selected based on the hash and protects mutations
37 * on a group of hash buckets.
38 *
a5ec68e3
TG
39 * A maximum of tbl->size/2 bucket locks is allocated. This ensures that
40 * a single lock always covers both buckets which may both contains
41 * entries which link to the same bucket of the old table during resizing.
42 * This allows to simplify the locking as locking the bucket in both
43 * tables during resize always guarantee protection.
44 *
97defe1e
TG
45 * IMPORTANT: When holding the bucket lock of both the old and new table
46 * during expansions and shrinking, the old bucket lock must always be
47 * acquired first.
48 */
49static spinlock_t *bucket_lock(const struct bucket_table *tbl, u32 hash)
50{
51 return &tbl->locks[hash & tbl->locks_mask];
52}
7e1e7763 53
c91eee56 54static void *rht_obj(const struct rhashtable *ht, const struct rhash_head *he)
7e1e7763
TG
55{
56 return (void *) he - ht->p.head_offset;
57}
7e1e7763 58
8d24c0b4 59static u32 rht_bucket_index(const struct bucket_table *tbl, u32 hash)
7e1e7763 60{
ec9f71c5 61 return (hash >> HASH_RESERVED_SPACE) & (tbl->size - 1);
7e1e7763
TG
62}
63
aa34a6cb 64static u32 key_hashfn(struct rhashtable *ht, const struct bucket_table *tbl,
cffaa9cb 65 const void *key)
7e1e7763 66{
cffaa9cb 67 return rht_bucket_index(tbl, ht->p.hashfn(key, ht->p.key_len,
ec9f71c5 68 tbl->hash_rnd));
7e1e7763 69}
7e1e7763 70
988dfbd7 71static u32 head_hashfn(struct rhashtable *ht,
8d24c0b4
TG
72 const struct bucket_table *tbl,
73 const struct rhash_head *he)
7e1e7763 74{
ec9f71c5
HX
75 const char *ptr = rht_obj(ht, he);
76
77 return likely(ht->p.key_len) ?
78 key_hashfn(ht, tbl, ptr + ht->p.key_offset) :
79 rht_bucket_index(tbl, ht->p.obj_hashfn(ptr, tbl->hash_rnd));
7e1e7763
TG
80}
81
a03eaec0 82#ifdef CONFIG_PROVE_LOCKING
a03eaec0 83#define ASSERT_RHT_MUTEX(HT) BUG_ON(!lockdep_rht_mutex_is_held(HT))
a03eaec0
TG
84
85int lockdep_rht_mutex_is_held(struct rhashtable *ht)
86{
87 return (debug_locks) ? lockdep_is_held(&ht->mutex) : 1;
88}
89EXPORT_SYMBOL_GPL(lockdep_rht_mutex_is_held);
90
91int lockdep_rht_bucket_is_held(const struct bucket_table *tbl, u32 hash)
92{
93 spinlock_t *lock = bucket_lock(tbl, hash);
94
95 return (debug_locks) ? lockdep_is_held(lock) : 1;
96}
97EXPORT_SYMBOL_GPL(lockdep_rht_bucket_is_held);
98#else
99#define ASSERT_RHT_MUTEX(HT)
a03eaec0
TG
100#endif
101
102
97defe1e
TG
103static int alloc_bucket_locks(struct rhashtable *ht, struct bucket_table *tbl)
104{
105 unsigned int i, size;
106#if defined(CONFIG_PROVE_LOCKING)
107 unsigned int nr_pcpus = 2;
108#else
109 unsigned int nr_pcpus = num_possible_cpus();
110#endif
111
112 nr_pcpus = min_t(unsigned int, nr_pcpus, 32UL);
113 size = roundup_pow_of_two(nr_pcpus * ht->p.locks_mul);
114
a5ec68e3
TG
115 /* Never allocate more than 0.5 locks per bucket */
116 size = min_t(unsigned int, size, tbl->size >> 1);
97defe1e
TG
117
118 if (sizeof(spinlock_t) != 0) {
119#ifdef CONFIG_NUMA
120 if (size * sizeof(spinlock_t) > PAGE_SIZE)
121 tbl->locks = vmalloc(size * sizeof(spinlock_t));
122 else
123#endif
124 tbl->locks = kmalloc_array(size, sizeof(spinlock_t),
125 GFP_KERNEL);
126 if (!tbl->locks)
127 return -ENOMEM;
128 for (i = 0; i < size; i++)
129 spin_lock_init(&tbl->locks[i]);
130 }
131 tbl->locks_mask = size - 1;
132
133 return 0;
134}
135
136static void bucket_table_free(const struct bucket_table *tbl)
137{
138 if (tbl)
139 kvfree(tbl->locks);
140
141 kvfree(tbl);
142}
143
144static struct bucket_table *bucket_table_alloc(struct rhashtable *ht,
a5b6846f 145 size_t nbuckets, u32 hash_rnd)
7e1e7763 146{
eb6d1abf 147 struct bucket_table *tbl = NULL;
7e1e7763 148 size_t size;
f89bd6f8 149 int i;
7e1e7763
TG
150
151 size = sizeof(*tbl) + nbuckets * sizeof(tbl->buckets[0]);
eb6d1abf
DB
152 if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER))
153 tbl = kzalloc(size, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY);
7e1e7763
TG
154 if (tbl == NULL)
155 tbl = vzalloc(size);
7e1e7763
TG
156 if (tbl == NULL)
157 return NULL;
158
159 tbl->size = nbuckets;
a5b6846f
DB
160 tbl->shift = ilog2(nbuckets);
161 tbl->hash_rnd = hash_rnd;
7e1e7763 162
97defe1e
TG
163 if (alloc_bucket_locks(ht, tbl) < 0) {
164 bucket_table_free(tbl);
165 return NULL;
166 }
7e1e7763 167
eddee5ba
HX
168 INIT_LIST_HEAD(&tbl->walkers);
169
f89bd6f8
TG
170 for (i = 0; i < nbuckets; i++)
171 INIT_RHT_NULLS_HEAD(tbl->buckets[i], ht, i);
172
97defe1e 173 return tbl;
7e1e7763
TG
174}
175
176/**
177 * rht_grow_above_75 - returns true if nelems > 0.75 * table-size
178 * @ht: hash table
a5b6846f 179 * @tbl: current table
7e1e7763 180 */
a5b6846f
DB
181static bool rht_grow_above_75(const struct rhashtable *ht,
182 const struct bucket_table *tbl)
7e1e7763
TG
183{
184 /* Expand table when exceeding 75% load */
a5b6846f
DB
185 return atomic_read(&ht->nelems) > (tbl->size / 4 * 3) &&
186 (!ht->p.max_shift || tbl->shift < ht->p.max_shift);
7e1e7763 187}
7e1e7763
TG
188
189/**
190 * rht_shrink_below_30 - returns true if nelems < 0.3 * table-size
191 * @ht: hash table
a5b6846f 192 * @tbl: current table
7e1e7763 193 */
a5b6846f
DB
194static bool rht_shrink_below_30(const struct rhashtable *ht,
195 const struct bucket_table *tbl)
7e1e7763
TG
196{
197 /* Shrink table beneath 30% load */
a5b6846f
DB
198 return atomic_read(&ht->nelems) < (tbl->size * 3 / 10) &&
199 tbl->shift > ht->p.min_shift;
7e1e7763 200}
7e1e7763 201
aa34a6cb 202static int rhashtable_rehash_one(struct rhashtable *ht, unsigned old_hash)
a5ec68e3 203{
aa34a6cb
HX
204 struct bucket_table *new_tbl = rht_dereference(ht->future_tbl, ht);
205 struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht);
206 struct rhash_head __rcu **pprev = &old_tbl->buckets[old_hash];
207 int err = -ENOENT;
208 struct rhash_head *head, *next, *entry;
209 spinlock_t *new_bucket_lock;
210 unsigned new_hash;
211
212 rht_for_each(entry, old_tbl, old_hash) {
213 err = 0;
214 next = rht_dereference_bucket(entry->next, old_tbl, old_hash);
215
216 if (rht_is_a_nulls(next))
217 break;
a5ec68e3 218
aa34a6cb
HX
219 pprev = &entry->next;
220 }
a5ec68e3 221
aa34a6cb
HX
222 if (err)
223 goto out;
97defe1e 224
aa34a6cb 225 new_hash = head_hashfn(ht, new_tbl, entry);
7e1e7763 226
aa34a6cb 227 new_bucket_lock = bucket_lock(new_tbl, new_hash);
7e1e7763 228
8f2484bd 229 spin_lock_nested(new_bucket_lock, SINGLE_DEPTH_NESTING);
aa34a6cb
HX
230 head = rht_dereference_bucket(new_tbl->buckets[new_hash],
231 new_tbl, new_hash);
97defe1e 232
aa34a6cb
HX
233 if (rht_is_a_nulls(head))
234 INIT_RHT_NULLS_HEAD(entry->next, ht, new_hash);
235 else
236 RCU_INIT_POINTER(entry->next, head);
a5ec68e3 237
aa34a6cb
HX
238 rcu_assign_pointer(new_tbl->buckets[new_hash], entry);
239 spin_unlock(new_bucket_lock);
97defe1e 240
aa34a6cb 241 rcu_assign_pointer(*pprev, next);
7e1e7763 242
aa34a6cb
HX
243out:
244 return err;
245}
97defe1e 246
aa34a6cb
HX
247static void rhashtable_rehash_chain(struct rhashtable *ht, unsigned old_hash)
248{
249 struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht);
250 spinlock_t *old_bucket_lock;
251
252 old_bucket_lock = bucket_lock(old_tbl, old_hash);
a5ec68e3 253
aa34a6cb
HX
254 spin_lock_bh(old_bucket_lock);
255 while (!rhashtable_rehash_one(ht, old_hash))
256 ;
257 spin_unlock_bh(old_bucket_lock);
97defe1e
TG
258}
259
aa34a6cb
HX
260static void rhashtable_rehash(struct rhashtable *ht,
261 struct bucket_table *new_tbl)
97defe1e 262{
aa34a6cb 263 struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht);
eddee5ba 264 struct rhashtable_walker *walker;
aa34a6cb 265 unsigned old_hash;
7cd10db8 266
aa34a6cb
HX
267 get_random_bytes(&new_tbl->hash_rnd, sizeof(new_tbl->hash_rnd));
268
269 /* Make insertions go into the new, empty table right away. Deletions
270 * and lookups will be attempted in both tables until we synchronize.
271 * The synchronize_rcu() guarantees for the new table to be picked up
272 * so no new additions go into the old table while we relink.
273 */
274 rcu_assign_pointer(ht->future_tbl, new_tbl);
275
9497df88
HX
276 /* Ensure the new table is visible to readers. */
277 smp_wmb();
278
aa34a6cb
HX
279 for (old_hash = 0; old_hash < old_tbl->size; old_hash++)
280 rhashtable_rehash_chain(ht, old_hash);
281
282 /* Publish the new table pointer. */
283 rcu_assign_pointer(ht->tbl, new_tbl);
284
eddee5ba
HX
285 list_for_each_entry(walker, &old_tbl->walkers, list)
286 walker->tbl = NULL;
287
aa34a6cb
HX
288 /* Wait for readers. All new readers will see the new
289 * table, and thus no references to the old table will
290 * remain.
291 */
292 synchronize_rcu();
293
294 bucket_table_free(old_tbl);
7e1e7763
TG
295}
296
297/**
298 * rhashtable_expand - Expand hash table while allowing concurrent lookups
299 * @ht: the hash table to expand
7e1e7763 300 *
aa34a6cb 301 * A secondary bucket array is allocated and the hash entries are migrated.
7e1e7763
TG
302 *
303 * This function may only be called in a context where it is safe to call
304 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
305 *
97defe1e
TG
306 * The caller must ensure that no concurrent resizing occurs by holding
307 * ht->mutex.
308 *
309 * It is valid to have concurrent insertions and deletions protected by per
310 * bucket locks or concurrent RCU protected lookups and traversals.
7e1e7763 311 */
6eba8224 312int rhashtable_expand(struct rhashtable *ht)
7e1e7763
TG
313{
314 struct bucket_table *new_tbl, *old_tbl = rht_dereference(ht->tbl, ht);
7e1e7763
TG
315
316 ASSERT_RHT_MUTEX(ht);
317
a5b6846f 318 new_tbl = bucket_table_alloc(ht, old_tbl->size * 2, old_tbl->hash_rnd);
7e1e7763
TG
319 if (new_tbl == NULL)
320 return -ENOMEM;
321
aa34a6cb 322 rhashtable_rehash(ht, new_tbl);
7e1e7763
TG
323 return 0;
324}
325EXPORT_SYMBOL_GPL(rhashtable_expand);
326
327/**
328 * rhashtable_shrink - Shrink hash table while allowing concurrent lookups
329 * @ht: the hash table to shrink
7e1e7763
TG
330 *
331 * This function may only be called in a context where it is safe to call
332 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
333 *
97defe1e
TG
334 * The caller must ensure that no concurrent resizing occurs by holding
335 * ht->mutex.
336 *
7e1e7763
TG
337 * The caller must ensure that no concurrent table mutations take place.
338 * It is however valid to have concurrent lookups if they are RCU protected.
97defe1e
TG
339 *
340 * It is valid to have concurrent insertions and deletions protected by per
341 * bucket locks or concurrent RCU protected lookups and traversals.
7e1e7763 342 */
6eba8224 343int rhashtable_shrink(struct rhashtable *ht)
7e1e7763 344{
a5b6846f 345 struct bucket_table *new_tbl, *old_tbl = rht_dereference(ht->tbl, ht);
7e1e7763
TG
346
347 ASSERT_RHT_MUTEX(ht);
348
a5b6846f 349 new_tbl = bucket_table_alloc(ht, old_tbl->size / 2, old_tbl->hash_rnd);
97defe1e 350 if (new_tbl == NULL)
7e1e7763
TG
351 return -ENOMEM;
352
aa34a6cb 353 rhashtable_rehash(ht, new_tbl);
7e1e7763
TG
354 return 0;
355}
356EXPORT_SYMBOL_GPL(rhashtable_shrink);
357
97defe1e
TG
358static void rht_deferred_worker(struct work_struct *work)
359{
360 struct rhashtable *ht;
361 struct bucket_table *tbl;
362
57699a40 363 ht = container_of(work, struct rhashtable, run_work);
97defe1e 364 mutex_lock(&ht->mutex);
28134a53
HX
365 if (ht->being_destroyed)
366 goto unlock;
367
97defe1e
TG
368 tbl = rht_dereference(ht->tbl, ht);
369
a5b6846f 370 if (rht_grow_above_75(ht, tbl))
97defe1e 371 rhashtable_expand(ht);
a5b6846f 372 else if (rht_shrink_below_30(ht, tbl))
97defe1e 373 rhashtable_shrink(ht);
28134a53 374unlock:
97defe1e
TG
375 mutex_unlock(&ht->mutex);
376}
377
aa34a6cb
HX
378static bool __rhashtable_insert(struct rhashtable *ht, struct rhash_head *obj,
379 bool (*compare)(void *, void *), void *arg)
db304854 380{
aa34a6cb 381 struct bucket_table *tbl, *old_tbl;
020219a6 382 struct rhash_head *head;
aa34a6cb
HX
383 bool no_resize_running;
384 unsigned hash;
385 bool success = true;
386
387 rcu_read_lock();
388
389 old_tbl = rht_dereference_rcu(ht->tbl, ht);
eca84933 390 hash = head_hashfn(ht, old_tbl, obj);
aa34a6cb
HX
391
392 spin_lock_bh(bucket_lock(old_tbl, hash));
393
394 /* Because we have already taken the bucket lock in old_tbl,
395 * if we find that future_tbl is not yet visible then that
396 * guarantees all other insertions of the same entry will
397 * also grab the bucket lock in old_tbl because until the
398 * rehash completes ht->tbl won't be changed.
399 */
400 tbl = rht_dereference_rcu(ht->future_tbl, ht);
401 if (tbl != old_tbl) {
eca84933 402 hash = head_hashfn(ht, tbl, obj);
8f2484bd 403 spin_lock_nested(bucket_lock(tbl, hash), SINGLE_DEPTH_NESTING);
aa34a6cb
HX
404 }
405
406 if (compare &&
407 rhashtable_lookup_compare(ht, rht_obj(ht, obj) + ht->p.key_offset,
408 compare, arg)) {
409 success = false;
410 goto exit;
411 }
412
413 no_resize_running = tbl == old_tbl;
020219a6 414
020219a6 415 head = rht_dereference_bucket(tbl->buckets[hash], tbl, hash);
db304854
YX
416
417 if (rht_is_a_nulls(head))
418 INIT_RHT_NULLS_HEAD(obj->next, ht, hash);
419 else
420 RCU_INIT_POINTER(obj->next, head);
421
422 rcu_assign_pointer(tbl->buckets[hash], obj);
423
424 atomic_inc(&ht->nelems);
a5b6846f 425 if (no_resize_running && rht_grow_above_75(ht, tbl))
4c4b52d9 426 schedule_work(&ht->run_work);
aa34a6cb
HX
427
428exit:
429 if (tbl != old_tbl) {
eca84933 430 hash = head_hashfn(ht, tbl, obj);
aa34a6cb
HX
431 spin_unlock(bucket_lock(tbl, hash));
432 }
433
eca84933 434 hash = head_hashfn(ht, old_tbl, obj);
aa34a6cb
HX
435 spin_unlock_bh(bucket_lock(old_tbl, hash));
436
437 rcu_read_unlock();
438
439 return success;
db304854
YX
440}
441
7e1e7763 442/**
db304854 443 * rhashtable_insert - insert object into hash table
7e1e7763
TG
444 * @ht: hash table
445 * @obj: pointer to hash head inside object
7e1e7763 446 *
97defe1e
TG
447 * Will take a per bucket spinlock to protect against mutual mutations
448 * on the same bucket. Multiple insertions may occur in parallel unless
449 * they map to the same bucket lock.
7e1e7763 450 *
97defe1e
TG
451 * It is safe to call this function from atomic context.
452 *
453 * Will trigger an automatic deferred table resizing if the size grows
454 * beyond the watermark indicated by grow_decision() which can be passed
455 * to rhashtable_init().
7e1e7763 456 */
6eba8224 457void rhashtable_insert(struct rhashtable *ht, struct rhash_head *obj)
7e1e7763 458{
aa34a6cb
HX
459 __rhashtable_insert(ht, obj, NULL, NULL);
460}
461EXPORT_SYMBOL_GPL(rhashtable_insert);
462
463static bool __rhashtable_remove(struct rhashtable *ht,
464 struct bucket_table *tbl,
465 struct rhash_head *obj)
466{
467 struct rhash_head __rcu **pprev;
468 struct rhash_head *he;
469 spinlock_t * lock;
97defe1e 470 unsigned hash;
aa34a6cb 471 bool ret = false;
7e1e7763 472
eca84933 473 hash = head_hashfn(ht, tbl, obj);
aa34a6cb 474 lock = bucket_lock(tbl, hash);
7e1e7763 475
aa34a6cb 476 spin_lock_bh(lock);
97defe1e 477
aa34a6cb
HX
478 pprev = &tbl->buckets[hash];
479 rht_for_each(he, tbl, hash) {
480 if (he != obj) {
481 pprev = &he->next;
482 continue;
483 }
7e1e7763 484
aa34a6cb
HX
485 rcu_assign_pointer(*pprev, obj->next);
486 ret = true;
487 break;
488 }
489
490 spin_unlock_bh(lock);
491
492 return ret;
7e1e7763 493}
7e1e7763 494
7e1e7763
TG
495/**
496 * rhashtable_remove - remove object from hash table
497 * @ht: hash table
498 * @obj: pointer to hash head inside object
7e1e7763
TG
499 *
500 * Since the hash chain is single linked, the removal operation needs to
501 * walk the bucket chain upon removal. The removal operation is thus
502 * considerable slow if the hash table is not correctly sized.
503 *
db304854 504 * Will automatically shrink the table via rhashtable_expand() if the
7e1e7763
TG
505 * shrink_decision function specified at rhashtable_init() returns true.
506 *
507 * The caller must ensure that no concurrent table mutations occur. It is
508 * however valid to have concurrent lookups if they are RCU protected.
509 */
6eba8224 510bool rhashtable_remove(struct rhashtable *ht, struct rhash_head *obj)
7e1e7763 511{
aa34a6cb
HX
512 struct bucket_table *tbl, *old_tbl;
513 bool ret;
7e1e7763 514
97defe1e 515 rcu_read_lock();
7e1e7763 516
aa34a6cb
HX
517 old_tbl = rht_dereference_rcu(ht->tbl, ht);
518 ret = __rhashtable_remove(ht, old_tbl, obj);
7e1e7763 519
aa34a6cb
HX
520 /* Because we have already taken (and released) the bucket
521 * lock in old_tbl, if we find that future_tbl is not yet
522 * visible then that guarantees the entry to still be in
523 * old_tbl if it exists.
fe6a043c 524 */
aa34a6cb
HX
525 tbl = rht_dereference_rcu(ht->future_tbl, ht);
526 if (!ret && old_tbl != tbl)
527 ret = __rhashtable_remove(ht, tbl, obj);
fe6a043c
TG
528
529 if (ret) {
aa34a6cb 530 bool no_resize_running = tbl == old_tbl;
4c4b52d9 531
fe6a043c 532 atomic_dec(&ht->nelems);
a5b6846f 533 if (no_resize_running && rht_shrink_below_30(ht, tbl))
4c4b52d9 534 schedule_work(&ht->run_work);
fe6a043c
TG
535 }
536
97defe1e
TG
537 rcu_read_unlock();
538
fe6a043c 539 return ret;
7e1e7763
TG
540}
541EXPORT_SYMBOL_GPL(rhashtable_remove);
542
efb975a6
YX
543struct rhashtable_compare_arg {
544 struct rhashtable *ht;
545 const void *key;
546};
547
548static bool rhashtable_compare(void *ptr, void *arg)
549{
550 struct rhashtable_compare_arg *x = arg;
551 struct rhashtable *ht = x->ht;
552
553 return !memcmp(ptr + ht->p.key_offset, x->key, ht->p.key_len);
554}
555
7e1e7763
TG
556/**
557 * rhashtable_lookup - lookup key in hash table
558 * @ht: hash table
559 * @key: pointer to key
560 *
561 * Computes the hash value for the key and traverses the bucket chain looking
562 * for a entry with an identical key. The first matching entry is returned.
563 *
564 * This lookup function may only be used for fixed key hash table (key_len
db304854 565 * parameter set). It will BUG() if used inappropriately.
7e1e7763 566 *
97defe1e 567 * Lookups may occur in parallel with hashtable mutations and resizing.
7e1e7763 568 */
97defe1e 569void *rhashtable_lookup(struct rhashtable *ht, const void *key)
7e1e7763 570{
efb975a6
YX
571 struct rhashtable_compare_arg arg = {
572 .ht = ht,
573 .key = key,
574 };
7e1e7763
TG
575
576 BUG_ON(!ht->p.key_len);
577
efb975a6 578 return rhashtable_lookup_compare(ht, key, &rhashtable_compare, &arg);
7e1e7763
TG
579}
580EXPORT_SYMBOL_GPL(rhashtable_lookup);
581
582/**
583 * rhashtable_lookup_compare - search hash table with compare function
584 * @ht: hash table
8d24c0b4 585 * @key: the pointer to the key
7e1e7763
TG
586 * @compare: compare function, must return true on match
587 * @arg: argument passed on to compare function
588 *
589 * Traverses the bucket chain behind the provided hash value and calls the
590 * specified compare function for each entry.
591 *
97defe1e 592 * Lookups may occur in parallel with hashtable mutations and resizing.
7e1e7763
TG
593 *
594 * Returns the first entry on which the compare function returned true.
595 */
97defe1e 596void *rhashtable_lookup_compare(struct rhashtable *ht, const void *key,
7e1e7763
TG
597 bool (*compare)(void *, void *), void *arg)
598{
97defe1e 599 const struct bucket_table *tbl, *old_tbl;
7e1e7763 600 struct rhash_head *he;
8d24c0b4 601 u32 hash;
7e1e7763 602
97defe1e
TG
603 rcu_read_lock();
604
aa34a6cb 605 tbl = rht_dereference_rcu(ht->tbl, ht);
97defe1e 606restart:
39361947 607 hash = key_hashfn(ht, tbl, key);
8d2b1879 608 rht_for_each_rcu(he, tbl, hash) {
7e1e7763
TG
609 if (!compare(rht_obj(ht, he), arg))
610 continue;
97defe1e 611 rcu_read_unlock();
a4b18cda 612 return rht_obj(ht, he);
7e1e7763
TG
613 }
614
9497df88
HX
615 /* Ensure we see any new tables. */
616 smp_rmb();
617
aa34a6cb
HX
618 old_tbl = tbl;
619 tbl = rht_dereference_rcu(ht->future_tbl, ht);
620 if (unlikely(tbl != old_tbl))
97defe1e 621 goto restart;
97defe1e
TG
622 rcu_read_unlock();
623
7e1e7763
TG
624 return NULL;
625}
626EXPORT_SYMBOL_GPL(rhashtable_lookup_compare);
627
db304854
YX
628/**
629 * rhashtable_lookup_insert - lookup and insert object into hash table
630 * @ht: hash table
631 * @obj: pointer to hash head inside object
632 *
633 * Locks down the bucket chain in both the old and new table if a resize
634 * is in progress to ensure that writers can't remove from the old table
635 * and can't insert to the new table during the atomic operation of search
636 * and insertion. Searches for duplicates in both the old and new table if
637 * a resize is in progress.
638 *
639 * This lookup function may only be used for fixed key hash table (key_len
640 * parameter set). It will BUG() if used inappropriately.
641 *
642 * It is safe to call this function from atomic context.
643 *
644 * Will trigger an automatic deferred table resizing if the size grows
645 * beyond the watermark indicated by grow_decision() which can be passed
646 * to rhashtable_init().
647 */
648bool rhashtable_lookup_insert(struct rhashtable *ht, struct rhash_head *obj)
7a868d1e
YX
649{
650 struct rhashtable_compare_arg arg = {
651 .ht = ht,
652 .key = rht_obj(ht, obj) + ht->p.key_offset,
653 };
654
655 BUG_ON(!ht->p.key_len);
656
657 return rhashtable_lookup_compare_insert(ht, obj, &rhashtable_compare,
658 &arg);
659}
660EXPORT_SYMBOL_GPL(rhashtable_lookup_insert);
661
662/**
663 * rhashtable_lookup_compare_insert - search and insert object to hash table
664 * with compare function
665 * @ht: hash table
666 * @obj: pointer to hash head inside object
667 * @compare: compare function, must return true on match
668 * @arg: argument passed on to compare function
669 *
670 * Locks down the bucket chain in both the old and new table if a resize
671 * is in progress to ensure that writers can't remove from the old table
672 * and can't insert to the new table during the atomic operation of search
673 * and insertion. Searches for duplicates in both the old and new table if
674 * a resize is in progress.
675 *
676 * Lookups may occur in parallel with hashtable mutations and resizing.
677 *
678 * Will trigger an automatic deferred table resizing if the size grows
679 * beyond the watermark indicated by grow_decision() which can be passed
680 * to rhashtable_init().
681 */
682bool rhashtable_lookup_compare_insert(struct rhashtable *ht,
683 struct rhash_head *obj,
684 bool (*compare)(void *, void *),
685 void *arg)
db304854 686{
db304854
YX
687 BUG_ON(!ht->p.key_len);
688
aa34a6cb 689 return __rhashtable_insert(ht, obj, compare, arg);
db304854 690}
7a868d1e 691EXPORT_SYMBOL_GPL(rhashtable_lookup_compare_insert);
db304854 692
f2dba9c6
HX
693/**
694 * rhashtable_walk_init - Initialise an iterator
695 * @ht: Table to walk over
696 * @iter: Hash table Iterator
697 *
698 * This function prepares a hash table walk.
699 *
700 * Note that if you restart a walk after rhashtable_walk_stop you
701 * may see the same object twice. Also, you may miss objects if
702 * there are removals in between rhashtable_walk_stop and the next
703 * call to rhashtable_walk_start.
704 *
705 * For a completely stable walk you should construct your own data
706 * structure outside the hash table.
707 *
708 * This function may sleep so you must not call it from interrupt
709 * context or with spin locks held.
710 *
711 * You must call rhashtable_walk_exit if this function returns
712 * successfully.
713 */
714int rhashtable_walk_init(struct rhashtable *ht, struct rhashtable_iter *iter)
715{
716 iter->ht = ht;
717 iter->p = NULL;
718 iter->slot = 0;
719 iter->skip = 0;
720
721 iter->walker = kmalloc(sizeof(*iter->walker), GFP_KERNEL);
722 if (!iter->walker)
723 return -ENOMEM;
724
725 mutex_lock(&ht->mutex);
eddee5ba
HX
726 iter->walker->tbl = rht_dereference(ht->tbl, ht);
727 list_add(&iter->walker->list, &iter->walker->tbl->walkers);
f2dba9c6
HX
728 mutex_unlock(&ht->mutex);
729
730 return 0;
731}
732EXPORT_SYMBOL_GPL(rhashtable_walk_init);
733
734/**
735 * rhashtable_walk_exit - Free an iterator
736 * @iter: Hash table Iterator
737 *
738 * This function frees resources allocated by rhashtable_walk_init.
739 */
740void rhashtable_walk_exit(struct rhashtable_iter *iter)
741{
742 mutex_lock(&iter->ht->mutex);
eddee5ba
HX
743 if (iter->walker->tbl)
744 list_del(&iter->walker->list);
f2dba9c6
HX
745 mutex_unlock(&iter->ht->mutex);
746 kfree(iter->walker);
747}
748EXPORT_SYMBOL_GPL(rhashtable_walk_exit);
749
750/**
751 * rhashtable_walk_start - Start a hash table walk
752 * @iter: Hash table iterator
753 *
754 * Start a hash table walk. Note that we take the RCU lock in all
755 * cases including when we return an error. So you must always call
756 * rhashtable_walk_stop to clean up.
757 *
758 * Returns zero if successful.
759 *
760 * Returns -EAGAIN if resize event occured. Note that the iterator
761 * will rewind back to the beginning and you may use it immediately
762 * by calling rhashtable_walk_next.
763 */
764int rhashtable_walk_start(struct rhashtable_iter *iter)
765{
eddee5ba
HX
766 struct rhashtable *ht = iter->ht;
767
768 mutex_lock(&ht->mutex);
769
770 if (iter->walker->tbl)
771 list_del(&iter->walker->list);
772
f2dba9c6
HX
773 rcu_read_lock();
774
eddee5ba
HX
775 mutex_unlock(&ht->mutex);
776
777 if (!iter->walker->tbl) {
778 iter->walker->tbl = rht_dereference_rcu(ht->tbl, ht);
f2dba9c6
HX
779 return -EAGAIN;
780 }
781
782 return 0;
783}
784EXPORT_SYMBOL_GPL(rhashtable_walk_start);
785
786/**
787 * rhashtable_walk_next - Return the next object and advance the iterator
788 * @iter: Hash table iterator
789 *
790 * Note that you must call rhashtable_walk_stop when you are finished
791 * with the walk.
792 *
793 * Returns the next object or NULL when the end of the table is reached.
794 *
795 * Returns -EAGAIN if resize event occured. Note that the iterator
796 * will rewind back to the beginning and you may continue to use it.
797 */
798void *rhashtable_walk_next(struct rhashtable_iter *iter)
799{
eddee5ba 800 struct bucket_table *tbl = iter->walker->tbl;
f2dba9c6
HX
801 struct rhashtable *ht = iter->ht;
802 struct rhash_head *p = iter->p;
803 void *obj = NULL;
804
f2dba9c6
HX
805 if (p) {
806 p = rht_dereference_bucket_rcu(p->next, tbl, iter->slot);
807 goto next;
808 }
809
810 for (; iter->slot < tbl->size; iter->slot++) {
811 int skip = iter->skip;
812
813 rht_for_each_rcu(p, tbl, iter->slot) {
814 if (!skip)
815 break;
816 skip--;
817 }
818
819next:
820 if (!rht_is_a_nulls(p)) {
821 iter->skip++;
822 iter->p = p;
823 obj = rht_obj(ht, p);
824 goto out;
825 }
826
827 iter->skip = 0;
828 }
829
eddee5ba
HX
830 iter->walker->tbl = rht_dereference_rcu(ht->future_tbl, ht);
831 if (iter->walker->tbl != tbl) {
f2dba9c6
HX
832 iter->slot = 0;
833 iter->skip = 0;
f2dba9c6
HX
834 return ERR_PTR(-EAGAIN);
835 }
836
eddee5ba
HX
837 iter->walker->tbl = NULL;
838 iter->p = NULL;
839
840out:
841
f2dba9c6
HX
842 return obj;
843}
844EXPORT_SYMBOL_GPL(rhashtable_walk_next);
845
846/**
847 * rhashtable_walk_stop - Finish a hash table walk
848 * @iter: Hash table iterator
849 *
850 * Finish a hash table walk.
851 */
852void rhashtable_walk_stop(struct rhashtable_iter *iter)
853{
eddee5ba
HX
854 struct rhashtable *ht;
855 struct bucket_table *tbl = iter->walker->tbl;
856
f2dba9c6 857 rcu_read_unlock();
eddee5ba
HX
858
859 if (!tbl)
860 return;
861
862 ht = iter->ht;
863
864 mutex_lock(&ht->mutex);
865 if (rht_dereference(ht->tbl, ht) == tbl ||
866 rht_dereference(ht->future_tbl, ht) == tbl)
867 list_add(&iter->walker->list, &tbl->walkers);
868 else
869 iter->walker->tbl = NULL;
870 mutex_unlock(&ht->mutex);
871
f2dba9c6
HX
872 iter->p = NULL;
873}
874EXPORT_SYMBOL_GPL(rhashtable_walk_stop);
875
94000176 876static size_t rounded_hashtable_size(struct rhashtable_params *params)
7e1e7763 877{
94000176
YX
878 return max(roundup_pow_of_two(params->nelem_hint * 4 / 3),
879 1UL << params->min_shift);
7e1e7763
TG
880}
881
882/**
883 * rhashtable_init - initialize a new hash table
884 * @ht: hash table to be initialized
885 * @params: configuration parameters
886 *
887 * Initializes a new hash table based on the provided configuration
888 * parameters. A table can be configured either with a variable or
889 * fixed length key:
890 *
891 * Configuration Example 1: Fixed length keys
892 * struct test_obj {
893 * int key;
894 * void * my_member;
895 * struct rhash_head node;
896 * };
897 *
898 * struct rhashtable_params params = {
899 * .head_offset = offsetof(struct test_obj, node),
900 * .key_offset = offsetof(struct test_obj, key),
901 * .key_len = sizeof(int),
87545899 902 * .hashfn = jhash,
f89bd6f8 903 * .nulls_base = (1U << RHT_BASE_SHIFT),
7e1e7763
TG
904 * };
905 *
906 * Configuration Example 2: Variable length keys
907 * struct test_obj {
908 * [...]
909 * struct rhash_head node;
910 * };
911 *
912 * u32 my_hash_fn(const void *data, u32 seed)
913 * {
914 * struct test_obj *obj = data;
915 *
916 * return [... hash ...];
917 * }
918 *
919 * struct rhashtable_params params = {
920 * .head_offset = offsetof(struct test_obj, node),
87545899 921 * .hashfn = jhash,
7e1e7763 922 * .obj_hashfn = my_hash_fn,
7e1e7763
TG
923 * };
924 */
925int rhashtable_init(struct rhashtable *ht, struct rhashtable_params *params)
926{
927 struct bucket_table *tbl;
928 size_t size;
a5b6846f 929 u32 hash_rnd;
7e1e7763
TG
930
931 size = HASH_DEFAULT_SIZE;
932
933 if ((params->key_len && !params->hashfn) ||
934 (!params->key_len && !params->obj_hashfn))
935 return -EINVAL;
936
f89bd6f8
TG
937 if (params->nulls_base && params->nulls_base < (1U << RHT_BASE_SHIFT))
938 return -EINVAL;
939
94000176
YX
940 params->min_shift = max_t(size_t, params->min_shift,
941 ilog2(HASH_MIN_SIZE));
942
7e1e7763 943 if (params->nelem_hint)
94000176 944 size = rounded_hashtable_size(params);
7e1e7763 945
97defe1e
TG
946 memset(ht, 0, sizeof(*ht));
947 mutex_init(&ht->mutex);
948 memcpy(&ht->p, params, sizeof(*params));
949
950 if (params->locks_mul)
951 ht->p.locks_mul = roundup_pow_of_two(params->locks_mul);
952 else
953 ht->p.locks_mul = BUCKET_LOCKS_PER_CPU;
954
a5b6846f
DB
955 get_random_bytes(&hash_rnd, sizeof(hash_rnd));
956
957 tbl = bucket_table_alloc(ht, size, hash_rnd);
7e1e7763
TG
958 if (tbl == NULL)
959 return -ENOMEM;
960
545a148e 961 atomic_set(&ht->nelems, 0);
a5b6846f 962
7e1e7763 963 RCU_INIT_POINTER(ht->tbl, tbl);
97defe1e 964 RCU_INIT_POINTER(ht->future_tbl, tbl);
7e1e7763 965
4c4b52d9 966 INIT_WORK(&ht->run_work, rht_deferred_worker);
97defe1e 967
7e1e7763
TG
968 return 0;
969}
970EXPORT_SYMBOL_GPL(rhashtable_init);
971
972/**
973 * rhashtable_destroy - destroy hash table
974 * @ht: the hash table to destroy
975 *
ae82ddcf
PNA
976 * Frees the bucket array. This function is not rcu safe, therefore the caller
977 * has to make sure that no resizing may happen by unpublishing the hashtable
978 * and waiting for the quiescent cycle before releasing the bucket array.
7e1e7763 979 */
97defe1e 980void rhashtable_destroy(struct rhashtable *ht)
7e1e7763 981{
97defe1e
TG
982 ht->being_destroyed = true;
983
4c4b52d9 984 cancel_work_sync(&ht->run_work);
97defe1e 985
57699a40 986 mutex_lock(&ht->mutex);
97defe1e 987 bucket_table_free(rht_dereference(ht->tbl, ht));
97defe1e 988 mutex_unlock(&ht->mutex);
7e1e7763
TG
989}
990EXPORT_SYMBOL_GPL(rhashtable_destroy);