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