Merge branch 'listener_refactor'
[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
274 for (old_hash = 0; old_hash < old_tbl->size; old_hash++)
275 rhashtable_rehash_chain(ht, old_hash);
276
277 /* Publish the new table pointer. */
278 rcu_assign_pointer(ht->tbl, new_tbl);
279
280 /* Wait for readers. All new readers will see the new
281 * table, and thus no references to the old table will
282 * remain.
283 */
284 synchronize_rcu();
285
286 bucket_table_free(old_tbl);
7e1e7763
TG
287}
288
289/**
290 * rhashtable_expand - Expand hash table while allowing concurrent lookups
291 * @ht: the hash table to expand
7e1e7763 292 *
aa34a6cb 293 * A secondary bucket array is allocated and the hash entries are migrated.
7e1e7763
TG
294 *
295 * This function may only be called in a context where it is safe to call
296 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
297 *
97defe1e
TG
298 * The caller must ensure that no concurrent resizing occurs by holding
299 * ht->mutex.
300 *
301 * It is valid to have concurrent insertions and deletions protected by per
302 * bucket locks or concurrent RCU protected lookups and traversals.
7e1e7763 303 */
6eba8224 304int rhashtable_expand(struct rhashtable *ht)
7e1e7763
TG
305{
306 struct bucket_table *new_tbl, *old_tbl = rht_dereference(ht->tbl, ht);
7e1e7763
TG
307
308 ASSERT_RHT_MUTEX(ht);
309
97defe1e 310 new_tbl = bucket_table_alloc(ht, old_tbl->size * 2);
7e1e7763
TG
311 if (new_tbl == NULL)
312 return -ENOMEM;
313
988dfbd7
HX
314 new_tbl->hash_rnd = old_tbl->hash_rnd;
315
c0c09bfd 316 atomic_inc(&ht->shift);
7e1e7763 317
aa34a6cb 318 rhashtable_rehash(ht, new_tbl);
7e1e7763 319
7e1e7763
TG
320 return 0;
321}
322EXPORT_SYMBOL_GPL(rhashtable_expand);
323
324/**
325 * rhashtable_shrink - Shrink hash table while allowing concurrent lookups
326 * @ht: the hash table to shrink
7e1e7763
TG
327 *
328 * This function may only be called in a context where it is safe to call
329 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
330 *
97defe1e
TG
331 * The caller must ensure that no concurrent resizing occurs by holding
332 * ht->mutex.
333 *
7e1e7763
TG
334 * The caller must ensure that no concurrent table mutations take place.
335 * It is however valid to have concurrent lookups if they are RCU protected.
97defe1e
TG
336 *
337 * It is valid to have concurrent insertions and deletions protected by per
338 * bucket locks or concurrent RCU protected lookups and traversals.
7e1e7763 339 */
6eba8224 340int rhashtable_shrink(struct rhashtable *ht)
7e1e7763 341{
97defe1e 342 struct bucket_table *new_tbl, *tbl = rht_dereference(ht->tbl, ht);
7e1e7763
TG
343
344 ASSERT_RHT_MUTEX(ht);
345
97defe1e
TG
346 new_tbl = bucket_table_alloc(ht, tbl->size / 2);
347 if (new_tbl == NULL)
7e1e7763
TG
348 return -ENOMEM;
349
988dfbd7
HX
350 new_tbl->hash_rnd = tbl->hash_rnd;
351
c0c09bfd 352 atomic_dec(&ht->shift);
7e1e7763 353
aa34a6cb 354 rhashtable_rehash(ht, new_tbl);
7e1e7763
TG
355
356 return 0;
357}
358EXPORT_SYMBOL_GPL(rhashtable_shrink);
359
97defe1e
TG
360static void rht_deferred_worker(struct work_struct *work)
361{
362 struct rhashtable *ht;
363 struct bucket_table *tbl;
f2dba9c6 364 struct rhashtable_walker *walker;
97defe1e 365
57699a40 366 ht = container_of(work, struct rhashtable, run_work);
97defe1e 367 mutex_lock(&ht->mutex);
28134a53
HX
368 if (ht->being_destroyed)
369 goto unlock;
370
97defe1e
TG
371 tbl = rht_dereference(ht->tbl, ht);
372
f2dba9c6
HX
373 list_for_each_entry(walker, &ht->walkers, list)
374 walker->resize = true;
375
4c4b52d9 376 if (rht_grow_above_75(ht, tbl->size))
97defe1e 377 rhashtable_expand(ht);
4c4b52d9 378 else if (rht_shrink_below_30(ht, tbl->size))
97defe1e 379 rhashtable_shrink(ht);
28134a53 380unlock:
97defe1e
TG
381 mutex_unlock(&ht->mutex);
382}
383
aa34a6cb
HX
384static bool __rhashtable_insert(struct rhashtable *ht, struct rhash_head *obj,
385 bool (*compare)(void *, void *), void *arg)
db304854 386{
aa34a6cb 387 struct bucket_table *tbl, *old_tbl;
020219a6 388 struct rhash_head *head;
aa34a6cb
HX
389 bool no_resize_running;
390 unsigned hash;
391 bool success = true;
392
393 rcu_read_lock();
394
395 old_tbl = rht_dereference_rcu(ht->tbl, ht);
eca84933 396 hash = head_hashfn(ht, old_tbl, obj);
aa34a6cb
HX
397
398 spin_lock_bh(bucket_lock(old_tbl, hash));
399
400 /* Because we have already taken the bucket lock in old_tbl,
401 * if we find that future_tbl is not yet visible then that
402 * guarantees all other insertions of the same entry will
403 * also grab the bucket lock in old_tbl because until the
404 * rehash completes ht->tbl won't be changed.
405 */
406 tbl = rht_dereference_rcu(ht->future_tbl, ht);
407 if (tbl != old_tbl) {
eca84933 408 hash = head_hashfn(ht, tbl, obj);
84ed82b7 409 spin_lock_nested(bucket_lock(tbl, hash), RHT_LOCK_NESTED);
aa34a6cb
HX
410 }
411
412 if (compare &&
413 rhashtable_lookup_compare(ht, rht_obj(ht, obj) + ht->p.key_offset,
414 compare, arg)) {
415 success = false;
416 goto exit;
417 }
418
419 no_resize_running = tbl == old_tbl;
020219a6 420
020219a6 421 head = rht_dereference_bucket(tbl->buckets[hash], tbl, hash);
db304854
YX
422
423 if (rht_is_a_nulls(head))
424 INIT_RHT_NULLS_HEAD(obj->next, ht, hash);
425 else
426 RCU_INIT_POINTER(obj->next, head);
427
428 rcu_assign_pointer(tbl->buckets[hash], obj);
429
430 atomic_inc(&ht->nelems);
4c4b52d9
DB
431 if (no_resize_running && rht_grow_above_75(ht, tbl->size))
432 schedule_work(&ht->run_work);
aa34a6cb
HX
433
434exit:
435 if (tbl != old_tbl) {
eca84933 436 hash = head_hashfn(ht, tbl, obj);
aa34a6cb
HX
437 spin_unlock(bucket_lock(tbl, hash));
438 }
439
eca84933 440 hash = head_hashfn(ht, old_tbl, obj);
aa34a6cb
HX
441 spin_unlock_bh(bucket_lock(old_tbl, hash));
442
443 rcu_read_unlock();
444
445 return success;
db304854
YX
446}
447
7e1e7763 448/**
db304854 449 * rhashtable_insert - insert object into hash table
7e1e7763
TG
450 * @ht: hash table
451 * @obj: pointer to hash head inside object
7e1e7763 452 *
97defe1e
TG
453 * Will take a per bucket spinlock to protect against mutual mutations
454 * on the same bucket. Multiple insertions may occur in parallel unless
455 * they map to the same bucket lock.
7e1e7763 456 *
97defe1e
TG
457 * It is safe to call this function from atomic context.
458 *
459 * Will trigger an automatic deferred table resizing if the size grows
460 * beyond the watermark indicated by grow_decision() which can be passed
461 * to rhashtable_init().
7e1e7763 462 */
6eba8224 463void rhashtable_insert(struct rhashtable *ht, struct rhash_head *obj)
7e1e7763 464{
aa34a6cb
HX
465 __rhashtable_insert(ht, obj, NULL, NULL);
466}
467EXPORT_SYMBOL_GPL(rhashtable_insert);
468
469static bool __rhashtable_remove(struct rhashtable *ht,
470 struct bucket_table *tbl,
471 struct rhash_head *obj)
472{
473 struct rhash_head __rcu **pprev;
474 struct rhash_head *he;
475 spinlock_t * lock;
97defe1e 476 unsigned hash;
aa34a6cb 477 bool ret = false;
7e1e7763 478
eca84933 479 hash = head_hashfn(ht, tbl, obj);
aa34a6cb 480 lock = bucket_lock(tbl, hash);
7e1e7763 481
aa34a6cb 482 spin_lock_bh(lock);
97defe1e 483
aa34a6cb
HX
484 pprev = &tbl->buckets[hash];
485 rht_for_each(he, tbl, hash) {
486 if (he != obj) {
487 pprev = &he->next;
488 continue;
489 }
7e1e7763 490
aa34a6cb
HX
491 rcu_assign_pointer(*pprev, obj->next);
492 ret = true;
493 break;
494 }
495
496 spin_unlock_bh(lock);
497
498 return ret;
7e1e7763 499}
7e1e7763 500
7e1e7763
TG
501/**
502 * rhashtable_remove - remove object from hash table
503 * @ht: hash table
504 * @obj: pointer to hash head inside object
7e1e7763
TG
505 *
506 * Since the hash chain is single linked, the removal operation needs to
507 * walk the bucket chain upon removal. The removal operation is thus
508 * considerable slow if the hash table is not correctly sized.
509 *
db304854 510 * Will automatically shrink the table via rhashtable_expand() if the
7e1e7763
TG
511 * shrink_decision function specified at rhashtable_init() returns true.
512 *
513 * The caller must ensure that no concurrent table mutations occur. It is
514 * however valid to have concurrent lookups if they are RCU protected.
515 */
6eba8224 516bool rhashtable_remove(struct rhashtable *ht, struct rhash_head *obj)
7e1e7763 517{
aa34a6cb
HX
518 struct bucket_table *tbl, *old_tbl;
519 bool ret;
7e1e7763 520
97defe1e 521 rcu_read_lock();
7e1e7763 522
aa34a6cb
HX
523 old_tbl = rht_dereference_rcu(ht->tbl, ht);
524 ret = __rhashtable_remove(ht, old_tbl, obj);
7e1e7763 525
aa34a6cb
HX
526 /* Because we have already taken (and released) the bucket
527 * lock in old_tbl, if we find that future_tbl is not yet
528 * visible then that guarantees the entry to still be in
529 * old_tbl if it exists.
fe6a043c 530 */
aa34a6cb
HX
531 tbl = rht_dereference_rcu(ht->future_tbl, ht);
532 if (!ret && old_tbl != tbl)
533 ret = __rhashtable_remove(ht, tbl, obj);
fe6a043c
TG
534
535 if (ret) {
aa34a6cb 536 bool no_resize_running = tbl == old_tbl;
4c4b52d9 537
fe6a043c 538 atomic_dec(&ht->nelems);
aa34a6cb 539 if (no_resize_running && rht_shrink_below_30(ht, tbl->size))
4c4b52d9 540 schedule_work(&ht->run_work);
fe6a043c
TG
541 }
542
97defe1e
TG
543 rcu_read_unlock();
544
fe6a043c 545 return ret;
7e1e7763
TG
546}
547EXPORT_SYMBOL_GPL(rhashtable_remove);
548
efb975a6
YX
549struct rhashtable_compare_arg {
550 struct rhashtable *ht;
551 const void *key;
552};
553
554static bool rhashtable_compare(void *ptr, void *arg)
555{
556 struct rhashtable_compare_arg *x = arg;
557 struct rhashtable *ht = x->ht;
558
559 return !memcmp(ptr + ht->p.key_offset, x->key, ht->p.key_len);
560}
561
7e1e7763
TG
562/**
563 * rhashtable_lookup - lookup key in hash table
564 * @ht: hash table
565 * @key: pointer to key
566 *
567 * Computes the hash value for the key and traverses the bucket chain looking
568 * for a entry with an identical key. The first matching entry is returned.
569 *
570 * This lookup function may only be used for fixed key hash table (key_len
db304854 571 * parameter set). It will BUG() if used inappropriately.
7e1e7763 572 *
97defe1e 573 * Lookups may occur in parallel with hashtable mutations and resizing.
7e1e7763 574 */
97defe1e 575void *rhashtable_lookup(struct rhashtable *ht, const void *key)
7e1e7763 576{
efb975a6
YX
577 struct rhashtable_compare_arg arg = {
578 .ht = ht,
579 .key = key,
580 };
7e1e7763
TG
581
582 BUG_ON(!ht->p.key_len);
583
efb975a6 584 return rhashtable_lookup_compare(ht, key, &rhashtable_compare, &arg);
7e1e7763
TG
585}
586EXPORT_SYMBOL_GPL(rhashtable_lookup);
587
588/**
589 * rhashtable_lookup_compare - search hash table with compare function
590 * @ht: hash table
8d24c0b4 591 * @key: the pointer to the key
7e1e7763
TG
592 * @compare: compare function, must return true on match
593 * @arg: argument passed on to compare function
594 *
595 * Traverses the bucket chain behind the provided hash value and calls the
596 * specified compare function for each entry.
597 *
97defe1e 598 * Lookups may occur in parallel with hashtable mutations and resizing.
7e1e7763
TG
599 *
600 * Returns the first entry on which the compare function returned true.
601 */
97defe1e 602void *rhashtable_lookup_compare(struct rhashtable *ht, const void *key,
7e1e7763
TG
603 bool (*compare)(void *, void *), void *arg)
604{
97defe1e 605 const struct bucket_table *tbl, *old_tbl;
7e1e7763 606 struct rhash_head *he;
8d24c0b4 607 u32 hash;
7e1e7763 608
97defe1e
TG
609 rcu_read_lock();
610
aa34a6cb 611 tbl = rht_dereference_rcu(ht->tbl, ht);
cffaa9cb 612 hash = key_hashfn(ht, tbl, key);
97defe1e 613restart:
8d2b1879 614 rht_for_each_rcu(he, tbl, hash) {
7e1e7763
TG
615 if (!compare(rht_obj(ht, he), arg))
616 continue;
97defe1e 617 rcu_read_unlock();
a4b18cda 618 return rht_obj(ht, he);
7e1e7763
TG
619 }
620
aa34a6cb
HX
621 old_tbl = tbl;
622 tbl = rht_dereference_rcu(ht->future_tbl, ht);
623 if (unlikely(tbl != old_tbl))
97defe1e 624 goto restart;
97defe1e
TG
625 rcu_read_unlock();
626
7e1e7763
TG
627 return NULL;
628}
629EXPORT_SYMBOL_GPL(rhashtable_lookup_compare);
630
db304854
YX
631/**
632 * rhashtable_lookup_insert - lookup and insert object into hash table
633 * @ht: hash table
634 * @obj: pointer to hash head inside object
635 *
636 * Locks down the bucket chain in both the old and new table if a resize
637 * is in progress to ensure that writers can't remove from the old table
638 * and can't insert to the new table during the atomic operation of search
639 * and insertion. Searches for duplicates in both the old and new table if
640 * a resize is in progress.
641 *
642 * This lookup function may only be used for fixed key hash table (key_len
643 * parameter set). It will BUG() if used inappropriately.
644 *
645 * It is safe to call this function from atomic context.
646 *
647 * Will trigger an automatic deferred table resizing if the size grows
648 * beyond the watermark indicated by grow_decision() which can be passed
649 * to rhashtable_init().
650 */
651bool rhashtable_lookup_insert(struct rhashtable *ht, struct rhash_head *obj)
7a868d1e
YX
652{
653 struct rhashtable_compare_arg arg = {
654 .ht = ht,
655 .key = rht_obj(ht, obj) + ht->p.key_offset,
656 };
657
658 BUG_ON(!ht->p.key_len);
659
660 return rhashtable_lookup_compare_insert(ht, obj, &rhashtable_compare,
661 &arg);
662}
663EXPORT_SYMBOL_GPL(rhashtable_lookup_insert);
664
665/**
666 * rhashtable_lookup_compare_insert - search and insert object to hash table
667 * with compare function
668 * @ht: hash table
669 * @obj: pointer to hash head inside object
670 * @compare: compare function, must return true on match
671 * @arg: argument passed on to compare function
672 *
673 * Locks down the bucket chain in both the old and new table if a resize
674 * is in progress to ensure that writers can't remove from the old table
675 * and can't insert to the new table during the atomic operation of search
676 * and insertion. Searches for duplicates in both the old and new table if
677 * a resize is in progress.
678 *
679 * Lookups may occur in parallel with hashtable mutations and resizing.
680 *
681 * Will trigger an automatic deferred table resizing if the size grows
682 * beyond the watermark indicated by grow_decision() which can be passed
683 * to rhashtable_init().
684 */
685bool rhashtable_lookup_compare_insert(struct rhashtable *ht,
686 struct rhash_head *obj,
687 bool (*compare)(void *, void *),
688 void *arg)
db304854 689{
db304854
YX
690 BUG_ON(!ht->p.key_len);
691
aa34a6cb 692 return __rhashtable_insert(ht, obj, compare, arg);
db304854 693}
7a868d1e 694EXPORT_SYMBOL_GPL(rhashtable_lookup_compare_insert);
db304854 695
f2dba9c6
HX
696/**
697 * rhashtable_walk_init - Initialise an iterator
698 * @ht: Table to walk over
699 * @iter: Hash table Iterator
700 *
701 * This function prepares a hash table walk.
702 *
703 * Note that if you restart a walk after rhashtable_walk_stop you
704 * may see the same object twice. Also, you may miss objects if
705 * there are removals in between rhashtable_walk_stop and the next
706 * call to rhashtable_walk_start.
707 *
708 * For a completely stable walk you should construct your own data
709 * structure outside the hash table.
710 *
711 * This function may sleep so you must not call it from interrupt
712 * context or with spin locks held.
713 *
714 * You must call rhashtable_walk_exit if this function returns
715 * successfully.
716 */
717int rhashtable_walk_init(struct rhashtable *ht, struct rhashtable_iter *iter)
718{
719 iter->ht = ht;
720 iter->p = NULL;
721 iter->slot = 0;
722 iter->skip = 0;
723
724 iter->walker = kmalloc(sizeof(*iter->walker), GFP_KERNEL);
725 if (!iter->walker)
726 return -ENOMEM;
727
71bb0012
SL
728 INIT_LIST_HEAD(&iter->walker->list);
729 iter->walker->resize = false;
730
f2dba9c6
HX
731 mutex_lock(&ht->mutex);
732 list_add(&iter->walker->list, &ht->walkers);
733 mutex_unlock(&ht->mutex);
734
735 return 0;
736}
737EXPORT_SYMBOL_GPL(rhashtable_walk_init);
738
739/**
740 * rhashtable_walk_exit - Free an iterator
741 * @iter: Hash table Iterator
742 *
743 * This function frees resources allocated by rhashtable_walk_init.
744 */
745void rhashtable_walk_exit(struct rhashtable_iter *iter)
746{
747 mutex_lock(&iter->ht->mutex);
748 list_del(&iter->walker->list);
749 mutex_unlock(&iter->ht->mutex);
750 kfree(iter->walker);
751}
752EXPORT_SYMBOL_GPL(rhashtable_walk_exit);
753
754/**
755 * rhashtable_walk_start - Start a hash table walk
756 * @iter: Hash table iterator
757 *
758 * Start a hash table walk. Note that we take the RCU lock in all
759 * cases including when we return an error. So you must always call
760 * rhashtable_walk_stop to clean up.
761 *
762 * Returns zero if successful.
763 *
764 * Returns -EAGAIN if resize event occured. Note that the iterator
765 * will rewind back to the beginning and you may use it immediately
766 * by calling rhashtable_walk_next.
767 */
768int rhashtable_walk_start(struct rhashtable_iter *iter)
769{
770 rcu_read_lock();
771
772 if (iter->walker->resize) {
773 iter->slot = 0;
774 iter->skip = 0;
775 iter->walker->resize = false;
776 return -EAGAIN;
777 }
778
779 return 0;
780}
781EXPORT_SYMBOL_GPL(rhashtable_walk_start);
782
783/**
784 * rhashtable_walk_next - Return the next object and advance the iterator
785 * @iter: Hash table iterator
786 *
787 * Note that you must call rhashtable_walk_stop when you are finished
788 * with the walk.
789 *
790 * Returns the next object or NULL when the end of the table is reached.
791 *
792 * Returns -EAGAIN if resize event occured. Note that the iterator
793 * will rewind back to the beginning and you may continue to use it.
794 */
795void *rhashtable_walk_next(struct rhashtable_iter *iter)
796{
797 const struct bucket_table *tbl;
798 struct rhashtable *ht = iter->ht;
799 struct rhash_head *p = iter->p;
800 void *obj = NULL;
801
802 tbl = rht_dereference_rcu(ht->tbl, ht);
803
804 if (p) {
805 p = rht_dereference_bucket_rcu(p->next, tbl, iter->slot);
806 goto next;
807 }
808
809 for (; iter->slot < tbl->size; iter->slot++) {
810 int skip = iter->skip;
811
812 rht_for_each_rcu(p, tbl, iter->slot) {
813 if (!skip)
814 break;
815 skip--;
816 }
817
818next:
819 if (!rht_is_a_nulls(p)) {
820 iter->skip++;
821 iter->p = p;
822 obj = rht_obj(ht, p);
823 goto out;
824 }
825
826 iter->skip = 0;
827 }
828
829 iter->p = NULL;
830
831out:
832 if (iter->walker->resize) {
833 iter->p = NULL;
834 iter->slot = 0;
835 iter->skip = 0;
836 iter->walker->resize = false;
837 return ERR_PTR(-EAGAIN);
838 }
839
840 return obj;
841}
842EXPORT_SYMBOL_GPL(rhashtable_walk_next);
843
844/**
845 * rhashtable_walk_stop - Finish a hash table walk
846 * @iter: Hash table iterator
847 *
848 * Finish a hash table walk.
849 */
850void rhashtable_walk_stop(struct rhashtable_iter *iter)
851{
852 rcu_read_unlock();
853 iter->p = NULL;
854}
855EXPORT_SYMBOL_GPL(rhashtable_walk_stop);
856
94000176 857static size_t rounded_hashtable_size(struct rhashtable_params *params)
7e1e7763 858{
94000176
YX
859 return max(roundup_pow_of_two(params->nelem_hint * 4 / 3),
860 1UL << params->min_shift);
7e1e7763
TG
861}
862
863/**
864 * rhashtable_init - initialize a new hash table
865 * @ht: hash table to be initialized
866 * @params: configuration parameters
867 *
868 * Initializes a new hash table based on the provided configuration
869 * parameters. A table can be configured either with a variable or
870 * fixed length key:
871 *
872 * Configuration Example 1: Fixed length keys
873 * struct test_obj {
874 * int key;
875 * void * my_member;
876 * struct rhash_head node;
877 * };
878 *
879 * struct rhashtable_params params = {
880 * .head_offset = offsetof(struct test_obj, node),
881 * .key_offset = offsetof(struct test_obj, key),
882 * .key_len = sizeof(int),
87545899 883 * .hashfn = jhash,
f89bd6f8 884 * .nulls_base = (1U << RHT_BASE_SHIFT),
7e1e7763
TG
885 * };
886 *
887 * Configuration Example 2: Variable length keys
888 * struct test_obj {
889 * [...]
890 * struct rhash_head node;
891 * };
892 *
893 * u32 my_hash_fn(const void *data, u32 seed)
894 * {
895 * struct test_obj *obj = data;
896 *
897 * return [... hash ...];
898 * }
899 *
900 * struct rhashtable_params params = {
901 * .head_offset = offsetof(struct test_obj, node),
87545899 902 * .hashfn = jhash,
7e1e7763 903 * .obj_hashfn = my_hash_fn,
7e1e7763
TG
904 * };
905 */
906int rhashtable_init(struct rhashtable *ht, struct rhashtable_params *params)
907{
908 struct bucket_table *tbl;
909 size_t size;
910
911 size = HASH_DEFAULT_SIZE;
912
913 if ((params->key_len && !params->hashfn) ||
914 (!params->key_len && !params->obj_hashfn))
915 return -EINVAL;
916
f89bd6f8
TG
917 if (params->nulls_base && params->nulls_base < (1U << RHT_BASE_SHIFT))
918 return -EINVAL;
919
94000176
YX
920 params->min_shift = max_t(size_t, params->min_shift,
921 ilog2(HASH_MIN_SIZE));
922
7e1e7763 923 if (params->nelem_hint)
94000176 924 size = rounded_hashtable_size(params);
7e1e7763 925
97defe1e
TG
926 memset(ht, 0, sizeof(*ht));
927 mutex_init(&ht->mutex);
928 memcpy(&ht->p, params, sizeof(*params));
f2dba9c6 929 INIT_LIST_HEAD(&ht->walkers);
97defe1e
TG
930
931 if (params->locks_mul)
932 ht->p.locks_mul = roundup_pow_of_two(params->locks_mul);
933 else
934 ht->p.locks_mul = BUCKET_LOCKS_PER_CPU;
935
936 tbl = bucket_table_alloc(ht, size);
7e1e7763
TG
937 if (tbl == NULL)
938 return -ENOMEM;
939
988dfbd7
HX
940 get_random_bytes(&tbl->hash_rnd, sizeof(tbl->hash_rnd));
941
545a148e 942 atomic_set(&ht->nelems, 0);
c0c09bfd 943 atomic_set(&ht->shift, ilog2(tbl->size));
7e1e7763 944 RCU_INIT_POINTER(ht->tbl, tbl);
97defe1e 945 RCU_INIT_POINTER(ht->future_tbl, tbl);
7e1e7763 946
4c4b52d9 947 INIT_WORK(&ht->run_work, rht_deferred_worker);
97defe1e 948
7e1e7763
TG
949 return 0;
950}
951EXPORT_SYMBOL_GPL(rhashtable_init);
952
953/**
954 * rhashtable_destroy - destroy hash table
955 * @ht: the hash table to destroy
956 *
ae82ddcf
PNA
957 * Frees the bucket array. This function is not rcu safe, therefore the caller
958 * has to make sure that no resizing may happen by unpublishing the hashtable
959 * and waiting for the quiescent cycle before releasing the bucket array.
7e1e7763 960 */
97defe1e 961void rhashtable_destroy(struct rhashtable *ht)
7e1e7763 962{
97defe1e
TG
963 ht->being_destroyed = true;
964
4c4b52d9 965 cancel_work_sync(&ht->run_work);
97defe1e 966
57699a40 967 mutex_lock(&ht->mutex);
97defe1e 968 bucket_table_free(rht_dereference(ht->tbl, ht));
97defe1e 969 mutex_unlock(&ht->mutex);
7e1e7763
TG
970}
971EXPORT_SYMBOL_GPL(rhashtable_destroy);