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