OSDN Git Service

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