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