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