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