]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blame - lib/rhashtable.c
rhashtable: introduce rhashtable_wakeup_worker helper function
[mirror_ubuntu-artful-kernel.git] / lib / rhashtable.c
CommitLineData
7e1e7763
TG
1/*
2 * Resizable, Scalable, Concurrent Hash Table
3 *
4 * Copyright (c) 2014 Thomas Graf <tgraf@suug.ch>
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,
37 RHT_LOCK_NESTED2,
38};
39
40/* The bucket lock is selected based on the hash and protects mutations
41 * on a group of hash buckets.
42 *
43 * IMPORTANT: When holding the bucket lock of both the old and new table
44 * during expansions and shrinking, the old bucket lock must always be
45 * acquired first.
46 */
47static spinlock_t *bucket_lock(const struct bucket_table *tbl, u32 hash)
48{
49 return &tbl->locks[hash & tbl->locks_mask];
50}
7e1e7763
TG
51
52#define ASSERT_RHT_MUTEX(HT) BUG_ON(!lockdep_rht_mutex_is_held(HT))
97defe1e
TG
53#define ASSERT_BUCKET_LOCK(TBL, HASH) \
54 BUG_ON(!lockdep_rht_bucket_is_held(TBL, HASH))
7e1e7763
TG
55
56#ifdef CONFIG_PROVE_LOCKING
97defe1e 57int lockdep_rht_mutex_is_held(struct rhashtable *ht)
7e1e7763 58{
97defe1e 59 return (debug_locks) ? lockdep_is_held(&ht->mutex) : 1;
7e1e7763
TG
60}
61EXPORT_SYMBOL_GPL(lockdep_rht_mutex_is_held);
88d6ed15
TG
62
63int lockdep_rht_bucket_is_held(const struct bucket_table *tbl, u32 hash)
64{
97defe1e
TG
65 spinlock_t *lock = bucket_lock(tbl, hash);
66
67 return (debug_locks) ? lockdep_is_held(lock) : 1;
88d6ed15
TG
68}
69EXPORT_SYMBOL_GPL(lockdep_rht_bucket_is_held);
7e1e7763
TG
70#endif
71
c91eee56 72static void *rht_obj(const struct rhashtable *ht, const struct rhash_head *he)
7e1e7763
TG
73{
74 return (void *) he - ht->p.head_offset;
75}
7e1e7763 76
8d24c0b4 77static u32 rht_bucket_index(const struct bucket_table *tbl, u32 hash)
7e1e7763 78{
8d24c0b4 79 return hash & (tbl->size - 1);
7e1e7763 80}
7e1e7763 81
8d24c0b4 82static u32 obj_raw_hashfn(const struct rhashtable *ht, const void *ptr)
7e1e7763 83{
8d24c0b4 84 u32 hash;
7e1e7763 85
8d24c0b4
TG
86 if (unlikely(!ht->p.key_len))
87 hash = ht->p.obj_hashfn(ptr, ht->p.hash_rnd);
88 else
89 hash = ht->p.hashfn(ptr + ht->p.key_offset, ht->p.key_len,
90 ht->p.hash_rnd);
7e1e7763 91
f89bd6f8 92 return hash >> HASH_RESERVED_SPACE;
7e1e7763
TG
93}
94
97defe1e 95static u32 key_hashfn(struct rhashtable *ht, const void *key, u32 len)
7e1e7763
TG
96{
97 struct bucket_table *tbl = rht_dereference_rcu(ht->tbl, ht);
8d24c0b4
TG
98 u32 hash;
99
100 hash = ht->p.hashfn(key, len, ht->p.hash_rnd);
f89bd6f8 101 hash >>= HASH_RESERVED_SPACE;
7e1e7763 102
8d24c0b4 103 return rht_bucket_index(tbl, hash);
7e1e7763 104}
7e1e7763
TG
105
106static u32 head_hashfn(const struct rhashtable *ht,
8d24c0b4
TG
107 const struct bucket_table *tbl,
108 const struct rhash_head *he)
7e1e7763 109{
8d24c0b4 110 return rht_bucket_index(tbl, obj_raw_hashfn(ht, rht_obj(ht, he)));
7e1e7763
TG
111}
112
b8e1943e
TG
113static struct rhash_head __rcu **bucket_tail(struct bucket_table *tbl, u32 n)
114{
115 struct rhash_head __rcu **pprev;
116
117 for (pprev = &tbl->buckets[n];
f89bd6f8 118 !rht_is_a_nulls(rht_dereference_bucket(*pprev, tbl, n));
b8e1943e
TG
119 pprev = &rht_dereference_bucket(*pprev, tbl, n)->next)
120 ;
121
122 return pprev;
123}
124
97defe1e
TG
125static int alloc_bucket_locks(struct rhashtable *ht, struct bucket_table *tbl)
126{
127 unsigned int i, size;
128#if defined(CONFIG_PROVE_LOCKING)
129 unsigned int nr_pcpus = 2;
130#else
131 unsigned int nr_pcpus = num_possible_cpus();
132#endif
133
134 nr_pcpus = min_t(unsigned int, nr_pcpus, 32UL);
135 size = roundup_pow_of_two(nr_pcpus * ht->p.locks_mul);
136
137 /* Never allocate more than one lock per bucket */
138 size = min_t(unsigned int, size, tbl->size);
139
140 if (sizeof(spinlock_t) != 0) {
141#ifdef CONFIG_NUMA
142 if (size * sizeof(spinlock_t) > PAGE_SIZE)
143 tbl->locks = vmalloc(size * sizeof(spinlock_t));
144 else
145#endif
146 tbl->locks = kmalloc_array(size, sizeof(spinlock_t),
147 GFP_KERNEL);
148 if (!tbl->locks)
149 return -ENOMEM;
150 for (i = 0; i < size; i++)
151 spin_lock_init(&tbl->locks[i]);
152 }
153 tbl->locks_mask = size - 1;
154
155 return 0;
156}
157
158static void bucket_table_free(const struct bucket_table *tbl)
159{
160 if (tbl)
161 kvfree(tbl->locks);
162
163 kvfree(tbl);
164}
165
166static struct bucket_table *bucket_table_alloc(struct rhashtable *ht,
167 size_t nbuckets)
7e1e7763
TG
168{
169 struct bucket_table *tbl;
170 size_t size;
f89bd6f8 171 int i;
7e1e7763
TG
172
173 size = sizeof(*tbl) + nbuckets * sizeof(tbl->buckets[0]);
6eba8224 174 tbl = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
7e1e7763
TG
175 if (tbl == NULL)
176 tbl = vzalloc(size);
177
178 if (tbl == NULL)
179 return NULL;
180
181 tbl->size = nbuckets;
182
97defe1e
TG
183 if (alloc_bucket_locks(ht, tbl) < 0) {
184 bucket_table_free(tbl);
185 return NULL;
186 }
7e1e7763 187
f89bd6f8
TG
188 for (i = 0; i < nbuckets; i++)
189 INIT_RHT_NULLS_HEAD(tbl->buckets[i], ht, i);
190
97defe1e 191 return tbl;
7e1e7763
TG
192}
193
194/**
195 * rht_grow_above_75 - returns true if nelems > 0.75 * table-size
196 * @ht: hash table
197 * @new_size: new table size
198 */
199bool rht_grow_above_75(const struct rhashtable *ht, size_t new_size)
200{
201 /* Expand table when exceeding 75% load */
97defe1e 202 return atomic_read(&ht->nelems) > (new_size / 4 * 3);
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 */
97defe1e 214 return atomic_read(&ht->nelems) < (new_size * 3 / 10);
7e1e7763
TG
215}
216EXPORT_SYMBOL_GPL(rht_shrink_below_30);
217
218static void hashtable_chain_unzip(const struct rhashtable *ht,
219 const struct bucket_table *new_tbl,
97defe1e
TG
220 struct bucket_table *old_tbl,
221 size_t old_hash)
7e1e7763
TG
222{
223 struct rhash_head *he, *p, *next;
97defe1e
TG
224 spinlock_t *new_bucket_lock, *new_bucket_lock2 = NULL;
225 unsigned int new_hash, new_hash2;
226
227 ASSERT_BUCKET_LOCK(old_tbl, old_hash);
7e1e7763
TG
228
229 /* Old bucket empty, no work needed. */
97defe1e
TG
230 p = rht_dereference_bucket(old_tbl->buckets[old_hash], old_tbl,
231 old_hash);
f89bd6f8 232 if (rht_is_a_nulls(p))
7e1e7763
TG
233 return;
234
97defe1e
TG
235 new_hash = new_hash2 = head_hashfn(ht, new_tbl, p);
236 new_bucket_lock = bucket_lock(new_tbl, new_hash);
237
7e1e7763
TG
238 /* Advance the old bucket pointer one or more times until it
239 * reaches a node that doesn't hash to the same bucket as the
240 * previous node p. Call the previous node p;
241 */
97defe1e
TG
242 rht_for_each_continue(he, p->next, old_tbl, old_hash) {
243 new_hash2 = head_hashfn(ht, new_tbl, he);
244 if (new_hash != new_hash2)
7e1e7763
TG
245 break;
246 p = he;
247 }
97defe1e
TG
248 rcu_assign_pointer(old_tbl->buckets[old_hash], p->next);
249
250 spin_lock_bh_nested(new_bucket_lock, RHT_LOCK_NESTED);
251
252 /* If we have encountered an entry that maps to a different bucket in
253 * the new table, lock down that bucket as well as we might cut off
254 * the end of the chain.
255 */
256 new_bucket_lock2 = bucket_lock(new_tbl, new_hash);
257 if (new_bucket_lock != new_bucket_lock2)
258 spin_lock_bh_nested(new_bucket_lock2, RHT_LOCK_NESTED2);
7e1e7763
TG
259
260 /* Find the subsequent node which does hash to the same
261 * bucket as node P, or NULL if no such node exists.
262 */
f89bd6f8
TG
263 INIT_RHT_NULLS_HEAD(next, ht, old_hash);
264 if (!rht_is_a_nulls(he)) {
97defe1e
TG
265 rht_for_each_continue(he, he->next, old_tbl, old_hash) {
266 if (head_hashfn(ht, new_tbl, he) == new_hash) {
7e1e7763
TG
267 next = he;
268 break;
269 }
270 }
271 }
272
273 /* Set p's next pointer to that subsequent node pointer,
274 * bypassing the nodes which do not hash to p's bucket
275 */
97defe1e
TG
276 rcu_assign_pointer(p->next, next);
277
278 if (new_bucket_lock != new_bucket_lock2)
279 spin_unlock_bh(new_bucket_lock2);
280 spin_unlock_bh(new_bucket_lock);
281}
282
283static void link_old_to_new(struct bucket_table *new_tbl,
284 unsigned int new_hash, struct rhash_head *entry)
285{
286 spinlock_t *new_bucket_lock;
287
288 new_bucket_lock = bucket_lock(new_tbl, new_hash);
289
290 spin_lock_bh_nested(new_bucket_lock, RHT_LOCK_NESTED);
291 rcu_assign_pointer(*bucket_tail(new_tbl, new_hash), entry);
292 spin_unlock_bh(new_bucket_lock);
7e1e7763
TG
293}
294
295/**
296 * rhashtable_expand - Expand hash table while allowing concurrent lookups
297 * @ht: the hash table to expand
7e1e7763
TG
298 *
299 * A secondary bucket array is allocated and the hash entries are migrated
300 * while keeping them on both lists until the end of the RCU grace period.
301 *
302 * This function may only be called in a context where it is safe to call
303 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
304 *
97defe1e
TG
305 * The caller must ensure that no concurrent resizing occurs by holding
306 * ht->mutex.
307 *
308 * It is valid to have concurrent insertions and deletions protected by per
309 * bucket locks or concurrent RCU protected lookups and traversals.
7e1e7763 310 */
6eba8224 311int rhashtable_expand(struct rhashtable *ht)
7e1e7763
TG
312{
313 struct bucket_table *new_tbl, *old_tbl = rht_dereference(ht->tbl, ht);
314 struct rhash_head *he;
97defe1e
TG
315 spinlock_t *old_bucket_lock;
316 unsigned int new_hash, old_hash;
317 bool complete = false;
7e1e7763
TG
318
319 ASSERT_RHT_MUTEX(ht);
320
321 if (ht->p.max_shift && ht->shift >= ht->p.max_shift)
322 return 0;
323
97defe1e 324 new_tbl = bucket_table_alloc(ht, old_tbl->size * 2);
7e1e7763
TG
325 if (new_tbl == NULL)
326 return -ENOMEM;
327
328 ht->shift++;
329
97defe1e
TG
330 /* Make insertions go into the new, empty table right away. Deletions
331 * and lookups will be attempted in both tables until we synchronize.
332 * The synchronize_rcu() guarantees for the new table to be picked up
333 * so no new additions go into the old table while we relink.
334 */
335 rcu_assign_pointer(ht->future_tbl, new_tbl);
336 synchronize_rcu();
337
338 /* For each new bucket, search the corresponding old bucket for the
339 * first entry that hashes to the new bucket, and link the end of
340 * newly formed bucket chain (containing entries added to future
341 * table) to that entry. Since all the entries which will end up in
342 * the new bucket appear in the same old bucket, this constructs an
343 * entirely valid new hash table, but with multiple buckets
344 * "zipped" together into a single imprecise chain.
7e1e7763 345 */
97defe1e
TG
346 for (new_hash = 0; new_hash < new_tbl->size; new_hash++) {
347 old_hash = rht_bucket_index(old_tbl, new_hash);
348 old_bucket_lock = bucket_lock(old_tbl, old_hash);
349
350 spin_lock_bh(old_bucket_lock);
351 rht_for_each(he, old_tbl, old_hash) {
352 if (head_hashfn(ht, new_tbl, he) == new_hash) {
353 link_old_to_new(new_tbl, new_hash, he);
7e1e7763
TG
354 break;
355 }
356 }
97defe1e 357 spin_unlock_bh(old_bucket_lock);
7e1e7763
TG
358 }
359
360 /* Publish the new table pointer. Lookups may now traverse
0c828f2f
HX
361 * the new table, but they will not benefit from any
362 * additional efficiency until later steps unzip the buckets.
7e1e7763
TG
363 */
364 rcu_assign_pointer(ht->tbl, new_tbl);
365
366 /* Unzip interleaved hash chains */
97defe1e 367 while (!complete && !ht->being_destroyed) {
7e1e7763
TG
368 /* Wait for readers. All new readers will see the new
369 * table, and thus no references to the old table will
370 * remain.
371 */
372 synchronize_rcu();
373
374 /* For each bucket in the old table (each of which
375 * contains items from multiple buckets of the new
376 * table): ...
377 */
378 complete = true;
97defe1e 379 for (old_hash = 0; old_hash < old_tbl->size; old_hash++) {
f89bd6f8
TG
380 struct rhash_head *head;
381
97defe1e
TG
382 old_bucket_lock = bucket_lock(old_tbl, old_hash);
383 spin_lock_bh(old_bucket_lock);
384
385 hashtable_chain_unzip(ht, new_tbl, old_tbl, old_hash);
f89bd6f8
TG
386 head = rht_dereference_bucket(old_tbl->buckets[old_hash],
387 old_tbl, old_hash);
388 if (!rht_is_a_nulls(head))
7e1e7763 389 complete = false;
97defe1e
TG
390
391 spin_unlock_bh(old_bucket_lock);
7e1e7763 392 }
97defe1e 393 }
7e1e7763
TG
394
395 bucket_table_free(old_tbl);
396 return 0;
397}
398EXPORT_SYMBOL_GPL(rhashtable_expand);
399
400/**
401 * rhashtable_shrink - Shrink hash table while allowing concurrent lookups
402 * @ht: the hash table to shrink
7e1e7763
TG
403 *
404 * This function may only be called in a context where it is safe to call
405 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
406 *
97defe1e
TG
407 * The caller must ensure that no concurrent resizing occurs by holding
408 * ht->mutex.
409 *
7e1e7763
TG
410 * The caller must ensure that no concurrent table mutations take place.
411 * It is however valid to have concurrent lookups if they are RCU protected.
97defe1e
TG
412 *
413 * It is valid to have concurrent insertions and deletions protected by per
414 * bucket locks or concurrent RCU protected lookups and traversals.
7e1e7763 415 */
6eba8224 416int rhashtable_shrink(struct rhashtable *ht)
7e1e7763 417{
97defe1e
TG
418 struct bucket_table *new_tbl, *tbl = rht_dereference(ht->tbl, ht);
419 spinlock_t *new_bucket_lock, *old_bucket_lock1, *old_bucket_lock2;
420 unsigned int new_hash;
7e1e7763
TG
421
422 ASSERT_RHT_MUTEX(ht);
423
94000176 424 if (ht->shift <= ht->p.min_shift)
7e1e7763
TG
425 return 0;
426
97defe1e
TG
427 new_tbl = bucket_table_alloc(ht, tbl->size / 2);
428 if (new_tbl == NULL)
7e1e7763
TG
429 return -ENOMEM;
430
97defe1e
TG
431 rcu_assign_pointer(ht->future_tbl, new_tbl);
432 synchronize_rcu();
7e1e7763 433
97defe1e
TG
434 /* Link the first entry in the old bucket to the end of the
435 * bucket in the new table. As entries are concurrently being
436 * added to the new table, lock down the new bucket. As we
437 * always divide the size in half when shrinking, each bucket
438 * in the new table maps to exactly two buckets in the old
439 * table.
440 *
441 * As removals can occur concurrently on the old table, we need
442 * to lock down both matching buckets in the old table.
7e1e7763 443 */
97defe1e
TG
444 for (new_hash = 0; new_hash < new_tbl->size; new_hash++) {
445 old_bucket_lock1 = bucket_lock(tbl, new_hash);
446 old_bucket_lock2 = bucket_lock(tbl, new_hash + new_tbl->size);
447 new_bucket_lock = bucket_lock(new_tbl, new_hash);
448
449 spin_lock_bh(old_bucket_lock1);
450 spin_lock_bh_nested(old_bucket_lock2, RHT_LOCK_NESTED);
451 spin_lock_bh_nested(new_bucket_lock, RHT_LOCK_NESTED2);
452
453 rcu_assign_pointer(*bucket_tail(new_tbl, new_hash),
454 tbl->buckets[new_hash]);
455 rcu_assign_pointer(*bucket_tail(new_tbl, new_hash),
456 tbl->buckets[new_hash + new_tbl->size]);
457
458 spin_unlock_bh(new_bucket_lock);
459 spin_unlock_bh(old_bucket_lock2);
460 spin_unlock_bh(old_bucket_lock1);
7e1e7763
TG
461 }
462
463 /* Publish the new, valid hash table */
97defe1e
TG
464 rcu_assign_pointer(ht->tbl, new_tbl);
465 ht->shift--;
7e1e7763
TG
466
467 /* Wait for readers. No new readers will have references to the
468 * old hash table.
469 */
470 synchronize_rcu();
471
472 bucket_table_free(tbl);
473
474 return 0;
475}
476EXPORT_SYMBOL_GPL(rhashtable_shrink);
477
97defe1e
TG
478static void rht_deferred_worker(struct work_struct *work)
479{
480 struct rhashtable *ht;
481 struct bucket_table *tbl;
482
483 ht = container_of(work, struct rhashtable, run_work.work);
484 mutex_lock(&ht->mutex);
485 tbl = rht_dereference(ht->tbl, ht);
486
487 if (ht->p.grow_decision && ht->p.grow_decision(ht, tbl->size))
488 rhashtable_expand(ht);
489 else if (ht->p.shrink_decision && ht->p.shrink_decision(ht, tbl->size))
490 rhashtable_shrink(ht);
491
492 mutex_unlock(&ht->mutex);
493}
494
54c5b7d3
YX
495static void rhashtable_wakeup_worker(struct rhashtable *ht)
496{
497 struct bucket_table *tbl = rht_dereference_rcu(ht->tbl, ht);
498 struct bucket_table *new_tbl = rht_dereference_rcu(ht->future_tbl, ht);
499 size_t size = tbl->size;
500
501 /* Only adjust the table if no resizing is currently in progress. */
502 if (tbl == new_tbl &&
503 ((ht->p.grow_decision && ht->p.grow_decision(ht, size)) ||
504 (ht->p.shrink_decision && ht->p.shrink_decision(ht, size))))
505 schedule_delayed_work(&ht->run_work, 0);
506}
507
7e1e7763
TG
508/**
509 * rhashtable_insert - insert object into hash hash table
510 * @ht: hash table
511 * @obj: pointer to hash head inside object
7e1e7763 512 *
97defe1e
TG
513 * Will take a per bucket spinlock to protect against mutual mutations
514 * on the same bucket. Multiple insertions may occur in parallel unless
515 * they map to the same bucket lock.
7e1e7763 516 *
97defe1e
TG
517 * It is safe to call this function from atomic context.
518 *
519 * Will trigger an automatic deferred table resizing if the size grows
520 * beyond the watermark indicated by grow_decision() which can be passed
521 * to rhashtable_init().
7e1e7763 522 */
6eba8224 523void rhashtable_insert(struct rhashtable *ht, struct rhash_head *obj)
7e1e7763 524{
97defe1e 525 struct bucket_table *tbl;
f89bd6f8 526 struct rhash_head *head;
97defe1e
TG
527 spinlock_t *lock;
528 unsigned hash;
7e1e7763 529
97defe1e 530 rcu_read_lock();
7e1e7763 531
97defe1e 532 tbl = rht_dereference_rcu(ht->future_tbl, ht);
8d24c0b4 533 hash = head_hashfn(ht, tbl, obj);
97defe1e
TG
534 lock = bucket_lock(tbl, hash);
535
536 spin_lock_bh(lock);
f89bd6f8
TG
537 head = rht_dereference_bucket(tbl->buckets[hash], tbl, hash);
538 if (rht_is_a_nulls(head))
539 INIT_RHT_NULLS_HEAD(obj->next, ht, hash);
540 else
541 RCU_INIT_POINTER(obj->next, head);
542
7e1e7763 543 rcu_assign_pointer(tbl->buckets[hash], obj);
97defe1e 544 spin_unlock_bh(lock);
7e1e7763 545
97defe1e
TG
546 atomic_inc(&ht->nelems);
547
54c5b7d3 548 rhashtable_wakeup_worker(ht);
97defe1e
TG
549
550 rcu_read_unlock();
7e1e7763
TG
551}
552EXPORT_SYMBOL_GPL(rhashtable_insert);
553
7e1e7763
TG
554/**
555 * rhashtable_remove - remove object from hash table
556 * @ht: hash table
557 * @obj: pointer to hash head inside object
7e1e7763
TG
558 *
559 * Since the hash chain is single linked, the removal operation needs to
560 * walk the bucket chain upon removal. The removal operation is thus
561 * considerable slow if the hash table is not correctly sized.
562 *
563 * Will automatically shrink the table via rhashtable_expand() if the the
564 * shrink_decision function specified at rhashtable_init() returns true.
565 *
566 * The caller must ensure that no concurrent table mutations occur. It is
567 * however valid to have concurrent lookups if they are RCU protected.
568 */
6eba8224 569bool rhashtable_remove(struct rhashtable *ht, struct rhash_head *obj)
7e1e7763 570{
97defe1e 571 struct bucket_table *tbl;
7e1e7763
TG
572 struct rhash_head __rcu **pprev;
573 struct rhash_head *he;
97defe1e
TG
574 spinlock_t *lock;
575 unsigned int hash;
7e1e7763 576
97defe1e
TG
577 rcu_read_lock();
578 tbl = rht_dereference_rcu(ht->tbl, ht);
579 hash = head_hashfn(ht, tbl, obj);
7e1e7763 580
97defe1e
TG
581 lock = bucket_lock(tbl, hash);
582 spin_lock_bh(lock);
7e1e7763 583
97defe1e
TG
584restart:
585 pprev = &tbl->buckets[hash];
586 rht_for_each(he, tbl, hash) {
7e1e7763
TG
587 if (he != obj) {
588 pprev = &he->next;
589 continue;
590 }
591
97defe1e
TG
592 rcu_assign_pointer(*pprev, obj->next);
593 atomic_dec(&ht->nelems);
897362e4 594
97defe1e
TG
595 spin_unlock_bh(lock);
596
54c5b7d3 597 rhashtable_wakeup_worker(ht);
97defe1e
TG
598
599 rcu_read_unlock();
897362e4 600
7e1e7763
TG
601 return true;
602 }
603
97defe1e
TG
604 if (tbl != rht_dereference_rcu(ht->tbl, ht)) {
605 spin_unlock_bh(lock);
606
607 tbl = rht_dereference_rcu(ht->tbl, ht);
608 hash = head_hashfn(ht, tbl, obj);
609
610 lock = bucket_lock(tbl, hash);
611 spin_lock_bh(lock);
612 goto restart;
613 }
614
615 spin_unlock_bh(lock);
616 rcu_read_unlock();
617
7e1e7763
TG
618 return false;
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
644 * paramter set). It will BUG() if used inappropriately.
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
94000176 705static size_t rounded_hashtable_size(struct rhashtable_params *params)
7e1e7763 706{
94000176
YX
707 return max(roundup_pow_of_two(params->nelem_hint * 4 / 3),
708 1UL << params->min_shift);
7e1e7763
TG
709}
710
711/**
712 * rhashtable_init - initialize a new hash table
713 * @ht: hash table to be initialized
714 * @params: configuration parameters
715 *
716 * Initializes a new hash table based on the provided configuration
717 * parameters. A table can be configured either with a variable or
718 * fixed length key:
719 *
720 * Configuration Example 1: Fixed length keys
721 * struct test_obj {
722 * int key;
723 * void * my_member;
724 * struct rhash_head node;
725 * };
726 *
727 * struct rhashtable_params params = {
728 * .head_offset = offsetof(struct test_obj, node),
729 * .key_offset = offsetof(struct test_obj, key),
730 * .key_len = sizeof(int),
87545899 731 * .hashfn = jhash,
f89bd6f8 732 * .nulls_base = (1U << RHT_BASE_SHIFT),
7e1e7763
TG
733 * };
734 *
735 * Configuration Example 2: Variable length keys
736 * struct test_obj {
737 * [...]
738 * struct rhash_head node;
739 * };
740 *
741 * u32 my_hash_fn(const void *data, u32 seed)
742 * {
743 * struct test_obj *obj = data;
744 *
745 * return [... hash ...];
746 * }
747 *
748 * struct rhashtable_params params = {
749 * .head_offset = offsetof(struct test_obj, node),
87545899 750 * .hashfn = jhash,
7e1e7763 751 * .obj_hashfn = my_hash_fn,
7e1e7763
TG
752 * };
753 */
754int rhashtable_init(struct rhashtable *ht, struct rhashtable_params *params)
755{
756 struct bucket_table *tbl;
757 size_t size;
758
759 size = HASH_DEFAULT_SIZE;
760
761 if ((params->key_len && !params->hashfn) ||
762 (!params->key_len && !params->obj_hashfn))
763 return -EINVAL;
764
f89bd6f8
TG
765 if (params->nulls_base && params->nulls_base < (1U << RHT_BASE_SHIFT))
766 return -EINVAL;
767
94000176
YX
768 params->min_shift = max_t(size_t, params->min_shift,
769 ilog2(HASH_MIN_SIZE));
770
7e1e7763 771 if (params->nelem_hint)
94000176 772 size = rounded_hashtable_size(params);
7e1e7763 773
97defe1e
TG
774 memset(ht, 0, sizeof(*ht));
775 mutex_init(&ht->mutex);
776 memcpy(&ht->p, params, sizeof(*params));
777
778 if (params->locks_mul)
779 ht->p.locks_mul = roundup_pow_of_two(params->locks_mul);
780 else
781 ht->p.locks_mul = BUCKET_LOCKS_PER_CPU;
782
783 tbl = bucket_table_alloc(ht, size);
7e1e7763
TG
784 if (tbl == NULL)
785 return -ENOMEM;
786
7e1e7763 787 ht->shift = ilog2(tbl->size);
7e1e7763 788 RCU_INIT_POINTER(ht->tbl, tbl);
97defe1e 789 RCU_INIT_POINTER(ht->future_tbl, tbl);
7e1e7763
TG
790
791 if (!ht->p.hash_rnd)
792 get_random_bytes(&ht->p.hash_rnd, sizeof(ht->p.hash_rnd));
793
97defe1e
TG
794 if (ht->p.grow_decision || ht->p.shrink_decision)
795 INIT_DEFERRABLE_WORK(&ht->run_work, rht_deferred_worker);
796
7e1e7763
TG
797 return 0;
798}
799EXPORT_SYMBOL_GPL(rhashtable_init);
800
801/**
802 * rhashtable_destroy - destroy hash table
803 * @ht: the hash table to destroy
804 *
ae82ddcf
PNA
805 * Frees the bucket array. This function is not rcu safe, therefore the caller
806 * has to make sure that no resizing may happen by unpublishing the hashtable
807 * and waiting for the quiescent cycle before releasing the bucket array.
7e1e7763 808 */
97defe1e 809void rhashtable_destroy(struct rhashtable *ht)
7e1e7763 810{
97defe1e
TG
811 ht->being_destroyed = true;
812
813 mutex_lock(&ht->mutex);
814
815 cancel_delayed_work(&ht->run_work);
816 bucket_table_free(rht_dereference(ht->tbl, ht));
817
818 mutex_unlock(&ht->mutex);
7e1e7763
TG
819}
820EXPORT_SYMBOL_GPL(rhashtable_destroy);
821
822/**************************************************************************
823 * Self Test
824 **************************************************************************/
825
826#ifdef CONFIG_TEST_RHASHTABLE
827
828#define TEST_HT_SIZE 8
829#define TEST_ENTRIES 2048
830#define TEST_PTR ((void *) 0xdeadbeef)
831#define TEST_NEXPANDS 4
832
7e1e7763
TG
833struct test_obj {
834 void *ptr;
835 int value;
836 struct rhash_head node;
837};
838
839static int __init test_rht_lookup(struct rhashtable *ht)
840{
841 unsigned int i;
842
843 for (i = 0; i < TEST_ENTRIES * 2; i++) {
844 struct test_obj *obj;
845 bool expected = !(i % 2);
846 u32 key = i;
847
848 obj = rhashtable_lookup(ht, &key);
849
850 if (expected && !obj) {
851 pr_warn("Test failed: Could not find key %u\n", key);
852 return -ENOENT;
853 } else if (!expected && obj) {
854 pr_warn("Test failed: Unexpected entry found for key %u\n",
855 key);
856 return -EEXIST;
857 } else if (expected && obj) {
858 if (obj->ptr != TEST_PTR || obj->value != i) {
859 pr_warn("Test failed: Lookup value mismatch %p!=%p, %u!=%u\n",
860 obj->ptr, TEST_PTR, obj->value, i);
861 return -EINVAL;
862 }
863 }
864 }
865
866 return 0;
867}
868
3e7b2ec4 869static void test_bucket_stats(struct rhashtable *ht, bool quiet)
7e1e7763 870{
3e7b2ec4 871 unsigned int cnt, rcu_cnt, i, total = 0;
88d6ed15 872 struct rhash_head *pos;
7e1e7763 873 struct test_obj *obj;
3e7b2ec4 874 struct bucket_table *tbl;
7e1e7763 875
3e7b2ec4 876 tbl = rht_dereference_rcu(ht->tbl, ht);
7e1e7763 877 for (i = 0; i < tbl->size; i++) {
3e7b2ec4 878 rcu_cnt = cnt = 0;
7e1e7763
TG
879
880 if (!quiet)
881 pr_info(" [%#4x/%zu]", i, tbl->size);
882
88d6ed15 883 rht_for_each_entry_rcu(obj, pos, tbl, i, node) {
7e1e7763
TG
884 cnt++;
885 total++;
886 if (!quiet)
887 pr_cont(" [%p],", obj);
888 }
889
88d6ed15 890 rht_for_each_entry_rcu(obj, pos, tbl, i, node)
3e7b2ec4
TG
891 rcu_cnt++;
892
893 if (rcu_cnt != cnt)
894 pr_warn("Test failed: Chain count mismach %d != %d",
895 cnt, rcu_cnt);
896
7e1e7763
TG
897 if (!quiet)
898 pr_cont("\n [%#x] first element: %p, chain length: %u\n",
899 i, tbl->buckets[i], cnt);
900 }
901
97defe1e
TG
902 pr_info(" Traversal complete: counted=%u, nelems=%u, entries=%d\n",
903 total, atomic_read(&ht->nelems), TEST_ENTRIES);
3e7b2ec4 904
97defe1e 905 if (total != atomic_read(&ht->nelems) || total != TEST_ENTRIES)
3e7b2ec4 906 pr_warn("Test failed: Total count mismatch ^^^");
7e1e7763
TG
907}
908
909static int __init test_rhashtable(struct rhashtable *ht)
910{
911 struct bucket_table *tbl;
88d6ed15
TG
912 struct test_obj *obj;
913 struct rhash_head *pos, *next;
7e1e7763
TG
914 int err;
915 unsigned int i;
916
917 /*
918 * Insertion Test:
919 * Insert TEST_ENTRIES into table with all keys even numbers
920 */
921 pr_info(" Adding %d keys\n", TEST_ENTRIES);
922 for (i = 0; i < TEST_ENTRIES; i++) {
923 struct test_obj *obj;
924
925 obj = kzalloc(sizeof(*obj), GFP_KERNEL);
926 if (!obj) {
927 err = -ENOMEM;
928 goto error;
929 }
930
931 obj->ptr = TEST_PTR;
932 obj->value = i * 2;
933
6eba8224 934 rhashtable_insert(ht, &obj->node);
7e1e7763
TG
935 }
936
937 rcu_read_lock();
3e7b2ec4 938 test_bucket_stats(ht, true);
7e1e7763
TG
939 test_rht_lookup(ht);
940 rcu_read_unlock();
941
942 for (i = 0; i < TEST_NEXPANDS; i++) {
943 pr_info(" Table expansion iteration %u...\n", i);
97defe1e 944 mutex_lock(&ht->mutex);
6eba8224 945 rhashtable_expand(ht);
97defe1e 946 mutex_unlock(&ht->mutex);
7e1e7763
TG
947
948 rcu_read_lock();
949 pr_info(" Verifying lookups...\n");
950 test_rht_lookup(ht);
951 rcu_read_unlock();
952 }
953
954 for (i = 0; i < TEST_NEXPANDS; i++) {
955 pr_info(" Table shrinkage iteration %u...\n", i);
97defe1e 956 mutex_lock(&ht->mutex);
6eba8224 957 rhashtable_shrink(ht);
97defe1e 958 mutex_unlock(&ht->mutex);
7e1e7763
TG
959
960 rcu_read_lock();
961 pr_info(" Verifying lookups...\n");
962 test_rht_lookup(ht);
963 rcu_read_unlock();
964 }
965
3e7b2ec4
TG
966 rcu_read_lock();
967 test_bucket_stats(ht, true);
968 rcu_read_unlock();
969
7e1e7763
TG
970 pr_info(" Deleting %d keys\n", TEST_ENTRIES);
971 for (i = 0; i < TEST_ENTRIES; i++) {
972 u32 key = i * 2;
973
974 obj = rhashtable_lookup(ht, &key);
975 BUG_ON(!obj);
976
6eba8224 977 rhashtable_remove(ht, &obj->node);
7e1e7763
TG
978 kfree(obj);
979 }
980
981 return 0;
982
983error:
984 tbl = rht_dereference_rcu(ht->tbl, ht);
985 for (i = 0; i < tbl->size; i++)
88d6ed15 986 rht_for_each_entry_safe(obj, pos, next, tbl, i, node)
7e1e7763
TG
987 kfree(obj);
988
989 return err;
990}
991
992static int __init test_rht_init(void)
993{
994 struct rhashtable ht;
995 struct rhashtable_params params = {
996 .nelem_hint = TEST_HT_SIZE,
997 .head_offset = offsetof(struct test_obj, node),
998 .key_offset = offsetof(struct test_obj, value),
999 .key_len = sizeof(int),
87545899 1000 .hashfn = jhash,
f89bd6f8 1001 .nulls_base = (3U << RHT_BASE_SHIFT),
7e1e7763
TG
1002 .grow_decision = rht_grow_above_75,
1003 .shrink_decision = rht_shrink_below_30,
1004 };
1005 int err;
1006
1007 pr_info("Running resizable hashtable tests...\n");
1008
1009 err = rhashtable_init(&ht, &params);
1010 if (err < 0) {
1011 pr_warn("Test failed: Unable to initialize hashtable: %d\n",
1012 err);
1013 return err;
1014 }
1015
1016 err = test_rhashtable(&ht);
1017
1018 rhashtable_destroy(&ht);
1019
1020 return err;
1021}
1022
1023subsys_initcall(test_rht_init);
1024
1025#endif /* CONFIG_TEST_RHASHTABLE */