Added macros and headers to support SLES15
[compat-rdma/compat.git] / compat / rhashtable.c
1 /*
2  * Resizable, Scalable, Concurrent Hash Table
3  *
4  * Copyright (c) 2015 Herbert Xu <herbert@gondor.apana.org.au>
5  * Copyright (c) 2014-2015 Thomas Graf <tgraf@suug.ch>
6  * Copyright (c) 2008-2014 Patrick McHardy <kaber@trash.net>
7  *
8  * Code partially derived from nft_hash
9  * Rewritten with rehash code from br_multicast plus single list
10  * pointer as suggested by Josh Triplett
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/rhashtable.h>
18
19 #ifndef HAVE_RHLTABLE
20
21 #include <linux/atomic.h>
22 #include <linux/kernel.h>
23 #include <linux/init.h>
24 #include <linux/log2.h>
25 #include <linux/sched.h>
26 #include <linux/slab.h>
27 #include <linux/vmalloc.h>
28 #include <linux/mm.h>
29 #include <linux/jhash.h>
30 #include <linux/random.h>
31 #include <linux/err.h>
32 #include <linux/export.h>
33
34 #define HASH_DEFAULT_SIZE       64UL
35 #define HASH_MIN_SIZE           4U
36 #define BUCKET_LOCKS_PER_CPU    32UL
37
38 static u32 head_hashfn(struct rhashtable *ht,
39                        const struct bucket_table *tbl,
40                        const struct rhash_head *he)
41 {
42         return rht_head_hashfn(ht, tbl, he, ht->p);
43 }
44
45 #ifdef CONFIG_PROVE_LOCKING
46 #define ASSERT_RHT_MUTEX(HT) BUG_ON(!lockdep_rht_mutex_is_held(HT))
47
48 int lockdep_rht_mutex_is_held(struct rhashtable *ht)
49 {
50         return (debug_locks) ? lockdep_is_held(&ht->mutex) : 1;
51 }
52 EXPORT_SYMBOL_GPL(lockdep_rht_mutex_is_held);
53
54 int lockdep_rht_bucket_is_held(const struct bucket_table *tbl, u32 hash)
55 {
56         spinlock_t *lock = rht_bucket_lock(tbl, hash);
57
58         return (debug_locks) ? lockdep_is_held(lock) : 1;
59 }
60 EXPORT_SYMBOL_GPL(lockdep_rht_bucket_is_held);
61 #else
62 #define ASSERT_RHT_MUTEX(HT)
63 #endif
64
65
66 static int alloc_bucket_locks(struct rhashtable *ht, struct bucket_table *tbl,
67                               gfp_t gfp)
68 {
69         unsigned int i, size;
70 #if defined(CONFIG_PROVE_LOCKING)
71         unsigned int nr_pcpus = 2;
72 #else
73         unsigned int nr_pcpus = num_possible_cpus();
74 #endif
75
76         nr_pcpus = min_t(unsigned int, nr_pcpus, 64UL);
77         size = roundup_pow_of_two(nr_pcpus * ht->p.locks_mul);
78
79         /* Never allocate more than 0.5 locks per bucket */
80         size = min_t(unsigned int, size, tbl->size >> 1);
81
82         if (sizeof(spinlock_t) != 0) {
83                 tbl->locks = NULL;
84 #ifdef CONFIG_NUMA
85                 if (size * sizeof(spinlock_t) > PAGE_SIZE &&
86                     gfp == GFP_KERNEL)
87                         tbl->locks = vmalloc(size * sizeof(spinlock_t));
88 #endif
89                 if (gfp != GFP_KERNEL)
90                         gfp |= __GFP_NOWARN | __GFP_NORETRY;
91
92                 if (!tbl->locks)
93                         tbl->locks = kmalloc_array(size, sizeof(spinlock_t),
94                                                    gfp);
95                 if (!tbl->locks)
96                         return -ENOMEM;
97                 for (i = 0; i < size; i++)
98                         spin_lock_init(&tbl->locks[i]);
99         }
100         tbl->locks_mask = size - 1;
101
102         return 0;
103 }
104
105 static void bucket_table_free(const struct bucket_table *tbl)
106 {
107         if (tbl)
108                 kvfree(tbl->locks);
109
110         kvfree(tbl);
111 }
112
113 static void bucket_table_free_rcu(struct rcu_head *head)
114 {
115         bucket_table_free(container_of(head, struct bucket_table, rcu));
116 }
117
118 static struct bucket_table *bucket_table_alloc(struct rhashtable *ht,
119                                                size_t nbuckets,
120                                                gfp_t gfp)
121 {
122         struct bucket_table *tbl = NULL;
123         size_t size;
124         int i;
125
126         size = sizeof(*tbl) + nbuckets * sizeof(tbl->buckets[0]);
127         if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER) ||
128             gfp != GFP_KERNEL)
129                 tbl = kzalloc(size, gfp | __GFP_NOWARN | __GFP_NORETRY);
130         if (tbl == NULL && gfp == GFP_KERNEL)
131                 tbl = vzalloc(size);
132         if (tbl == NULL)
133                 return NULL;
134
135         tbl->size = nbuckets;
136
137         if (alloc_bucket_locks(ht, tbl, gfp) < 0) {
138                 bucket_table_free(tbl);
139                 return NULL;
140         }
141
142         INIT_LIST_HEAD(&tbl->walkers);
143
144         get_random_bytes(&tbl->hash_rnd, sizeof(tbl->hash_rnd));
145
146         for (i = 0; i < nbuckets; i++)
147                 INIT_RHT_NULLS_HEAD(tbl->buckets[i], ht, i);
148
149         return tbl;
150 }
151
152 static struct bucket_table *rhashtable_last_table(struct rhashtable *ht,
153                                                   struct bucket_table *tbl)
154 {
155         struct bucket_table *new_tbl;
156
157         do {
158                 new_tbl = tbl;
159                 tbl = rht_dereference_rcu(tbl->future_tbl, ht);
160         } while (tbl);
161
162         return new_tbl;
163 }
164
165 static int rhashtable_rehash_one(struct rhashtable *ht, unsigned int old_hash)
166 {
167         struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht);
168         struct bucket_table *new_tbl = rhashtable_last_table(ht,
169                 rht_dereference_rcu(old_tbl->future_tbl, ht));
170         struct rhash_head __rcu **pprev = &old_tbl->buckets[old_hash];
171         int err = -ENOENT;
172         struct rhash_head *head, *next, *entry;
173         spinlock_t *new_bucket_lock;
174         unsigned int new_hash;
175
176         rht_for_each(entry, old_tbl, old_hash) {
177                 err = 0;
178                 next = rht_dereference_bucket(entry->next, old_tbl, old_hash);
179
180                 if (rht_is_a_nulls(next))
181                         break;
182
183                 pprev = &entry->next;
184         }
185
186         if (err)
187                 goto out;
188
189         new_hash = head_hashfn(ht, new_tbl, entry);
190
191         new_bucket_lock = rht_bucket_lock(new_tbl, new_hash);
192
193         spin_lock_nested(new_bucket_lock, SINGLE_DEPTH_NESTING);
194         head = rht_dereference_bucket(new_tbl->buckets[new_hash],
195                                       new_tbl, new_hash);
196
197         RCU_INIT_POINTER(entry->next, head);
198
199         rcu_assign_pointer(new_tbl->buckets[new_hash], entry);
200         spin_unlock(new_bucket_lock);
201
202         rcu_assign_pointer(*pprev, next);
203
204 out:
205         return err;
206 }
207
208 static void rhashtable_rehash_chain(struct rhashtable *ht,
209                                     unsigned int old_hash)
210 {
211         struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht);
212         spinlock_t *old_bucket_lock;
213
214         old_bucket_lock = rht_bucket_lock(old_tbl, old_hash);
215
216         spin_lock_bh(old_bucket_lock);
217         while (!rhashtable_rehash_one(ht, old_hash))
218                 ;
219         old_tbl->rehash++;
220         spin_unlock_bh(old_bucket_lock);
221 }
222
223 static int rhashtable_rehash_attach(struct rhashtable *ht,
224                                     struct bucket_table *old_tbl,
225                                     struct bucket_table *new_tbl)
226 {
227         /* Protect future_tbl using the first bucket lock. */
228         spin_lock_bh(old_tbl->locks);
229
230         /* Did somebody beat us to it? */
231         if (rcu_access_pointer(old_tbl->future_tbl)) {
232                 spin_unlock_bh(old_tbl->locks);
233                 return -EEXIST;
234         }
235
236         /* Make insertions go into the new, empty table right away. Deletions
237          * and lookups will be attempted in both tables until we synchronize.
238          */
239         rcu_assign_pointer(old_tbl->future_tbl, new_tbl);
240
241         spin_unlock_bh(old_tbl->locks);
242
243         return 0;
244 }
245
246 static int rhashtable_rehash_table(struct rhashtable *ht)
247 {
248         struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht);
249         struct bucket_table *new_tbl;
250         struct rhashtable_walker *walker;
251         unsigned int old_hash;
252
253         new_tbl = rht_dereference(old_tbl->future_tbl, ht);
254         if (!new_tbl)
255                 return 0;
256
257         for (old_hash = 0; old_hash < old_tbl->size; old_hash++)
258                 rhashtable_rehash_chain(ht, old_hash);
259
260         /* Publish the new table pointer. */
261         rcu_assign_pointer(ht->tbl, new_tbl);
262
263         spin_lock(&ht->lock);
264         list_for_each_entry(walker, &old_tbl->walkers, list)
265                 walker->tbl = NULL;
266         spin_unlock(&ht->lock);
267
268         /* Wait for readers. All new readers will see the new
269          * table, and thus no references to the old table will
270          * remain.
271          */
272         call_rcu(&old_tbl->rcu, bucket_table_free_rcu);
273
274         return rht_dereference(new_tbl->future_tbl, ht) ? -EAGAIN : 0;
275 }
276
277 /**
278  * rhashtable_expand - Expand hash table while allowing concurrent lookups
279  * @ht:         the hash table to expand
280  *
281  * A secondary bucket array is allocated and the hash entries are migrated.
282  *
283  * This function may only be called in a context where it is safe to call
284  * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
285  *
286  * The caller must ensure that no concurrent resizing occurs by holding
287  * ht->mutex.
288  *
289  * It is valid to have concurrent insertions and deletions protected by per
290  * bucket locks or concurrent RCU protected lookups and traversals.
291  */
292 static int rhashtable_expand(struct rhashtable *ht)
293 {
294         struct bucket_table *new_tbl, *old_tbl = rht_dereference(ht->tbl, ht);
295         int err;
296
297         ASSERT_RHT_MUTEX(ht);
298
299         old_tbl = rhashtable_last_table(ht, old_tbl);
300
301         new_tbl = bucket_table_alloc(ht, old_tbl->size * 2, GFP_KERNEL);
302         if (new_tbl == NULL)
303                 return -ENOMEM;
304
305         err = rhashtable_rehash_attach(ht, old_tbl, new_tbl);
306         if (err)
307                 bucket_table_free(new_tbl);
308
309         return err;
310 }
311
312 /**
313  * rhashtable_shrink - Shrink hash table while allowing concurrent lookups
314  * @ht:         the hash table to shrink
315  *
316  * This function shrinks the hash table to fit, i.e., the smallest
317  * size would not cause it to expand right away automatically.
318  *
319  * The caller must ensure that no concurrent resizing occurs by holding
320  * ht->mutex.
321  *
322  * The caller must ensure that no concurrent table mutations take place.
323  * It is however valid to have concurrent lookups if they are RCU protected.
324  *
325  * It is valid to have concurrent insertions and deletions protected by per
326  * bucket locks or concurrent RCU protected lookups and traversals.
327  */
328 static int rhashtable_shrink(struct rhashtable *ht)
329 {
330         struct bucket_table *new_tbl, *old_tbl = rht_dereference(ht->tbl, ht);
331         unsigned int nelems = atomic_read(&ht->nelems);
332         unsigned int size = 0;
333         int err;
334
335         ASSERT_RHT_MUTEX(ht);
336
337         if (nelems)
338                 size = roundup_pow_of_two(nelems * 3 / 2);
339         if (size < ht->p.min_size)
340                 size = ht->p.min_size;
341
342         if (old_tbl->size <= size)
343                 return 0;
344
345         if (rht_dereference(old_tbl->future_tbl, ht))
346                 return -EEXIST;
347
348         new_tbl = bucket_table_alloc(ht, size, GFP_KERNEL);
349         if (new_tbl == NULL)
350                 return -ENOMEM;
351
352         err = rhashtable_rehash_attach(ht, old_tbl, new_tbl);
353         if (err)
354                 bucket_table_free(new_tbl);
355
356         return err;
357 }
358
359 static void rht_deferred_worker(struct work_struct *work)
360 {
361         struct rhashtable *ht;
362         struct bucket_table *tbl;
363         int err = 0;
364
365         ht = container_of(work, struct rhashtable, run_work);
366         mutex_lock(&ht->mutex);
367
368         tbl = rht_dereference(ht->tbl, ht);
369         tbl = rhashtable_last_table(ht, tbl);
370
371         if (rht_grow_above_75(ht, tbl))
372                 rhashtable_expand(ht);
373         else if (ht->p.automatic_shrinking && rht_shrink_below_30(ht, tbl))
374                 rhashtable_shrink(ht);
375
376         err = rhashtable_rehash_table(ht);
377
378         mutex_unlock(&ht->mutex);
379
380         if (err)
381                 schedule_work(&ht->run_work);
382 }
383
384 static int rhashtable_insert_rehash(struct rhashtable *ht,
385                                     struct bucket_table *tbl)
386 {
387         struct bucket_table *old_tbl;
388         struct bucket_table *new_tbl;
389         unsigned int size;
390         int err;
391
392         old_tbl = rht_dereference_rcu(ht->tbl, ht);
393
394         size = tbl->size;
395
396         err = -EBUSY;
397
398         if (rht_grow_above_75(ht, tbl))
399                 size *= 2;
400         /* Do not schedule more than one rehash */
401         else if (old_tbl != tbl)
402                 goto fail;
403
404         err = -ENOMEM;
405
406         new_tbl = bucket_table_alloc(ht, size, GFP_ATOMIC);
407         if (new_tbl == NULL)
408                 goto fail;
409
410         err = rhashtable_rehash_attach(ht, tbl, new_tbl);
411         if (err) {
412                 bucket_table_free(new_tbl);
413                 if (err == -EEXIST)
414                         err = 0;
415         } else
416                 schedule_work(&ht->run_work);
417
418         return err;
419
420 fail:
421         /* Do not fail the insert if someone else did a rehash. */
422         if (likely(rcu_dereference_raw(tbl->future_tbl)))
423                 return 0;
424
425         /* Schedule async rehash to retry allocation in process context. */
426         if (err == -ENOMEM)
427                 schedule_work(&ht->run_work);
428
429         return err;
430 }
431
432 static void *rhashtable_lookup_one(struct rhashtable *ht,
433                                    struct bucket_table *tbl, unsigned int hash,
434                                    const void *key, struct rhash_head *obj)
435 {
436         struct rhashtable_compare_arg arg = {
437                 .ht = ht,
438                 .key = key,
439         };
440         struct rhash_head __rcu **pprev;
441         struct rhash_head *head;
442         int elasticity;
443
444         elasticity = ht->elasticity;
445         pprev = &tbl->buckets[hash];
446         rht_for_each(head, tbl, hash) {
447                 struct rhlist_head *list;
448                 struct rhlist_head *plist;
449
450                 elasticity--;
451                 if (!key ||
452                     (ht->p.obj_cmpfn ?
453                      ht->p.obj_cmpfn(&arg, rht_obj(ht, head)) :
454                      rhashtable_compare(&arg, rht_obj(ht, head)))) {
455                         pprev = &head->next;
456                         continue;
457                 }
458
459                 if (!ht->rhlist)
460                         return rht_obj(ht, head);
461
462                 list = container_of(obj, struct rhlist_head, rhead);
463                 plist = container_of(head, struct rhlist_head, rhead);
464
465                 RCU_INIT_POINTER(list->next, plist);
466                 head = rht_dereference_bucket(head->next, tbl, hash);
467                 RCU_INIT_POINTER(list->rhead.next, head);
468                 rcu_assign_pointer(*pprev, obj);
469
470                 return NULL;
471         }
472
473         if (elasticity <= 0)
474                 return ERR_PTR(-EAGAIN);
475
476         return ERR_PTR(-ENOENT);
477 }
478
479 static struct bucket_table *rhashtable_insert_one(struct rhashtable *ht,
480                                                   struct bucket_table *tbl,
481                                                   unsigned int hash,
482                                                   struct rhash_head *obj,
483                                                   void *data)
484 {
485         struct bucket_table *new_tbl;
486         struct rhash_head *head;
487
488         if (!IS_ERR_OR_NULL(data))
489                 return ERR_PTR(-EEXIST);
490
491         if (PTR_ERR(data) != -EAGAIN && PTR_ERR(data) != -ENOENT)
492                 return ERR_CAST(data);
493
494         new_tbl = rcu_dereference(tbl->future_tbl);
495         if (new_tbl)
496                 return new_tbl;
497
498         if (PTR_ERR(data) != -ENOENT)
499                 return ERR_CAST(data);
500
501         if (unlikely(rht_grow_above_max(ht, tbl)))
502                 return ERR_PTR(-E2BIG);
503
504         if (unlikely(rht_grow_above_100(ht, tbl)))
505                 return ERR_PTR(-EAGAIN);
506
507         head = rht_dereference_bucket(tbl->buckets[hash], tbl, hash);
508
509         RCU_INIT_POINTER(obj->next, head);
510         if (ht->rhlist) {
511                 struct rhlist_head *list;
512
513                 list = container_of(obj, struct rhlist_head, rhead);
514                 RCU_INIT_POINTER(list->next, NULL);
515         }
516
517         rcu_assign_pointer(tbl->buckets[hash], obj);
518
519         atomic_inc(&ht->nelems);
520         if (rht_grow_above_75(ht, tbl))
521                 schedule_work(&ht->run_work);
522
523         return NULL;
524 }
525
526 static void *rhashtable_try_insert(struct rhashtable *ht, const void *key,
527                                    struct rhash_head *obj)
528 {
529         struct bucket_table *new_tbl;
530         struct bucket_table *tbl;
531         unsigned int hash;
532         spinlock_t *lock;
533         void *data;
534
535         tbl = rcu_dereference(ht->tbl);
536
537         /* All insertions must grab the oldest table containing
538          * the hashed bucket that is yet to be rehashed.
539          */
540         for (;;) {
541                 hash = rht_head_hashfn(ht, tbl, obj, ht->p);
542                 lock = rht_bucket_lock(tbl, hash);
543                 spin_lock_bh(lock);
544
545                 if (tbl->rehash <= hash)
546                         break;
547
548                 spin_unlock_bh(lock);
549                 tbl = rcu_dereference(tbl->future_tbl);
550         }
551
552         data = rhashtable_lookup_one(ht, tbl, hash, key, obj);
553         new_tbl = rhashtable_insert_one(ht, tbl, hash, obj, data);
554         if (PTR_ERR(new_tbl) != -EEXIST)
555                 data = ERR_CAST(new_tbl);
556
557         while (!IS_ERR_OR_NULL(new_tbl)) {
558                 tbl = new_tbl;
559                 hash = rht_head_hashfn(ht, tbl, obj, ht->p);
560                 spin_lock_nested(rht_bucket_lock(tbl, hash),
561                                  SINGLE_DEPTH_NESTING);
562
563                 data = rhashtable_lookup_one(ht, tbl, hash, key, obj);
564                 new_tbl = rhashtable_insert_one(ht, tbl, hash, obj, data);
565                 if (PTR_ERR(new_tbl) != -EEXIST)
566                         data = ERR_CAST(new_tbl);
567
568                 spin_unlock(rht_bucket_lock(tbl, hash));
569         }
570
571         spin_unlock_bh(lock);
572
573         if (PTR_ERR(data) == -EAGAIN)
574                 data = ERR_PTR(rhashtable_insert_rehash(ht, tbl) ?:
575                                -EAGAIN);
576
577         return data;
578 }
579
580 void *rhashtable_insert_slow(struct rhashtable *ht, const void *key,
581                              struct rhash_head *obj)
582 {
583         void *data;
584
585         do {
586                 rcu_read_lock();
587                 data = rhashtable_try_insert(ht, key, obj);
588                 rcu_read_unlock();
589         } while (PTR_ERR(data) == -EAGAIN);
590
591         return data;
592 }
593 EXPORT_SYMBOL_GPL(rhashtable_insert_slow);
594
595 /**
596  * rhashtable_walk_enter - Initialise an iterator
597  * @ht:         Table to walk over
598  * @iter:       Hash table Iterator
599  *
600  * This function prepares a hash table walk.
601  *
602  * Note that if you restart a walk after rhashtable_walk_stop you
603  * may see the same object twice.  Also, you may miss objects if
604  * there are removals in between rhashtable_walk_stop and the next
605  * call to rhashtable_walk_start.
606  *
607  * For a completely stable walk you should construct your own data
608  * structure outside the hash table.
609  *
610  * This function may sleep so you must not call it from interrupt
611  * context or with spin locks held.
612  *
613  * You must call rhashtable_walk_exit after this function returns.
614  */
615 void rhashtable_walk_enter(struct rhashtable *ht, struct rhashtable_iter *iter)
616 {
617         iter->ht = ht;
618         iter->p = NULL;
619         iter->slot = 0;
620         iter->skip = 0;
621
622         spin_lock(&ht->lock);
623         iter->walker.tbl =
624                 rcu_dereference_protected(ht->tbl, lockdep_is_held(&ht->lock));
625         list_add(&iter->walker.list, &iter->walker.tbl->walkers);
626         spin_unlock(&ht->lock);
627 }
628 EXPORT_SYMBOL_GPL(rhashtable_walk_enter);
629
630 /**
631  * rhashtable_walk_exit - Free an iterator
632  * @iter:       Hash table Iterator
633  *
634  * This function frees resources allocated by rhashtable_walk_init.
635  */
636 void rhashtable_walk_exit(struct rhashtable_iter *iter)
637 {
638         spin_lock(&iter->ht->lock);
639         if (iter->walker.tbl)
640                 list_del(&iter->walker.list);
641         spin_unlock(&iter->ht->lock);
642 }
643 EXPORT_SYMBOL_GPL(rhashtable_walk_exit);
644
645 /**
646  * rhashtable_walk_start - Start a hash table walk
647  * @iter:       Hash table iterator
648  *
649  * Start a hash table walk.  Note that we take the RCU lock in all
650  * cases including when we return an error.  So you must always call
651  * rhashtable_walk_stop to clean up.
652  *
653  * Returns zero if successful.
654  *
655  * Returns -EAGAIN if resize event occured.  Note that the iterator
656  * will rewind back to the beginning and you may use it immediately
657  * by calling rhashtable_walk_next.
658  */
659 int rhashtable_walk_start(struct rhashtable_iter *iter)
660         __acquires(RCU)
661 {
662         struct rhashtable *ht = iter->ht;
663
664         rcu_read_lock();
665
666         spin_lock(&ht->lock);
667         if (iter->walker.tbl)
668                 list_del(&iter->walker.list);
669         spin_unlock(&ht->lock);
670
671         if (!iter->walker.tbl) {
672                 iter->walker.tbl = rht_dereference_rcu(ht->tbl, ht);
673                 return -EAGAIN;
674         }
675
676         return 0;
677 }
678 EXPORT_SYMBOL_GPL(rhashtable_walk_start);
679
680 /**
681  * rhashtable_walk_next - Return the next object and advance the iterator
682  * @iter:       Hash table iterator
683  *
684  * Note that you must call rhashtable_walk_stop when you are finished
685  * with the walk.
686  *
687  * Returns the next object or NULL when the end of the table is reached.
688  *
689  * Returns -EAGAIN if resize event occured.  Note that the iterator
690  * will rewind back to the beginning and you may continue to use it.
691  */
692 void *rhashtable_walk_next(struct rhashtable_iter *iter)
693 {
694         struct bucket_table *tbl = iter->walker.tbl;
695         struct rhlist_head *list = iter->list;
696         struct rhashtable *ht = iter->ht;
697         struct rhash_head *p = iter->p;
698         bool rhlist = ht->rhlist;
699
700         if (p) {
701                 if (!rhlist || !(list = rcu_dereference(list->next))) {
702                         p = rcu_dereference(p->next);
703                         list = container_of(p, struct rhlist_head, rhead);
704                 }
705                 goto next;
706         }
707
708         for (; iter->slot < tbl->size; iter->slot++) {
709                 int skip = iter->skip;
710
711                 rht_for_each_rcu(p, tbl, iter->slot) {
712                         if (rhlist) {
713                                 list = container_of(p, struct rhlist_head,
714                                                     rhead);
715                                 do {
716                                         if (!skip)
717                                                 goto next;
718                                         skip--;
719                                         list = rcu_dereference(list->next);
720                                 } while (list);
721
722                                 continue;
723                         }
724                         if (!skip)
725                                 break;
726                         skip--;
727                 }
728
729 next:
730                 if (!rht_is_a_nulls(p)) {
731                         iter->skip++;
732                         iter->p = p;
733                         iter->list = list;
734                         return rht_obj(ht, rhlist ? &list->rhead : p);
735                 }
736
737                 iter->skip = 0;
738         }
739
740         iter->p = NULL;
741
742         /* Ensure we see any new tables. */
743         smp_rmb();
744
745         iter->walker.tbl = rht_dereference_rcu(tbl->future_tbl, ht);
746         if (iter->walker.tbl) {
747                 iter->slot = 0;
748                 iter->skip = 0;
749                 return ERR_PTR(-EAGAIN);
750         }
751
752         return NULL;
753 }
754 EXPORT_SYMBOL_GPL(rhashtable_walk_next);
755
756 /**
757  * rhashtable_walk_stop - Finish a hash table walk
758  * @iter:       Hash table iterator
759  *
760  * Finish a hash table walk.
761  */
762 void rhashtable_walk_stop(struct rhashtable_iter *iter)
763         __releases(RCU)
764 {
765         struct rhashtable *ht;
766         struct bucket_table *tbl = iter->walker.tbl;
767
768         if (!tbl)
769                 goto out;
770
771         ht = iter->ht;
772
773         spin_lock(&ht->lock);
774         if (tbl->rehash < tbl->size)
775                 list_add(&iter->walker.list, &tbl->walkers);
776         else
777                 iter->walker.tbl = NULL;
778         spin_unlock(&ht->lock);
779
780         iter->p = NULL;
781
782 out:
783         rcu_read_unlock();
784 }
785 EXPORT_SYMBOL_GPL(rhashtable_walk_stop);
786
787 static size_t rounded_hashtable_size(const struct rhashtable_params *params)
788 {
789         return max(roundup_pow_of_two(params->nelem_hint * 4 / 3),
790                    (unsigned long)params->min_size);
791 }
792
793 static u32 rhashtable_jhash2(const void *key, u32 length, u32 seed)
794 {
795         return jhash2(key, length, seed);
796 }
797
798 /**
799  * rhashtable_init - initialize a new hash table
800  * @ht:         hash table to be initialized
801  * @params:     configuration parameters
802  *
803  * Initializes a new hash table based on the provided configuration
804  * parameters. A table can be configured either with a variable or
805  * fixed length key:
806  *
807  * Configuration Example 1: Fixed length keys
808  * struct test_obj {
809  *      int                     key;
810  *      void *                  my_member;
811  *      struct rhash_head       node;
812  * };
813  *
814  * struct rhashtable_params params = {
815  *      .head_offset = offsetof(struct test_obj, node),
816  *      .key_offset = offsetof(struct test_obj, key),
817  *      .key_len = sizeof(int),
818  *      .hashfn = jhash,
819  *      .nulls_base = (1U << RHT_BASE_SHIFT),
820  * };
821  *
822  * Configuration Example 2: Variable length keys
823  * struct test_obj {
824  *      [...]
825  *      struct rhash_head       node;
826  * };
827  *
828  * u32 my_hash_fn(const void *data, u32 len, u32 seed)
829  * {
830  *      struct test_obj *obj = data;
831  *
832  *      return [... hash ...];
833  * }
834  *
835  * struct rhashtable_params params = {
836  *      .head_offset = offsetof(struct test_obj, node),
837  *      .hashfn = jhash,
838  *      .obj_hashfn = my_hash_fn,
839  * };
840  */
841 int rhashtable_init(struct rhashtable *ht,
842                     const struct rhashtable_params *params)
843 {
844         struct bucket_table *tbl;
845         size_t size;
846
847         size = HASH_DEFAULT_SIZE;
848
849         if ((!params->key_len && !params->obj_hashfn) ||
850             (params->obj_hashfn && !params->obj_cmpfn))
851                 return -EINVAL;
852
853         if (params->nulls_base && params->nulls_base < (1U << RHT_BASE_SHIFT))
854                 return -EINVAL;
855
856         memset(ht, 0, sizeof(*ht));
857         mutex_init(&ht->mutex);
858         spin_lock_init(&ht->lock);
859         memcpy(&ht->p, params, sizeof(*params));
860
861         if (params->min_size)
862                 ht->p.min_size = roundup_pow_of_two(params->min_size);
863
864         if (params->max_size)
865                 ht->p.max_size = rounddown_pow_of_two(params->max_size);
866
867         if (params->insecure_max_entries)
868                 ht->p.insecure_max_entries =
869                         rounddown_pow_of_two(params->insecure_max_entries);
870         else
871                 ht->p.insecure_max_entries = ht->p.max_size * 2;
872
873         ht->p.min_size = max(ht->p.min_size, HASH_MIN_SIZE);
874
875         if (params->nelem_hint)
876                 size = rounded_hashtable_size(&ht->p);
877
878         /* The maximum (not average) chain length grows with the
879          * size of the hash table, at a rate of (log N)/(log log N).
880          * The value of 16 is selected so that even if the hash
881          * table grew to 2^32 you would not expect the maximum
882          * chain length to exceed it unless we are under attack
883          * (or extremely unlucky).
884          *
885          * As this limit is only to detect attacks, we don't need
886          * to set it to a lower value as you'd need the chain
887          * length to vastly exceed 16 to have any real effect
888          * on the system.
889          */
890         if (!params->insecure_elasticity)
891                 ht->elasticity = 16;
892
893         if (params->locks_mul)
894                 ht->p.locks_mul = roundup_pow_of_two(params->locks_mul);
895         else
896                 ht->p.locks_mul = BUCKET_LOCKS_PER_CPU;
897
898         ht->key_len = ht->p.key_len;
899         if (!params->hashfn) {
900                 ht->p.hashfn = jhash;
901
902                 if (!(ht->key_len & (sizeof(u32) - 1))) {
903                         ht->key_len /= sizeof(u32);
904                         ht->p.hashfn = rhashtable_jhash2;
905                 }
906         }
907
908         tbl = bucket_table_alloc(ht, size, GFP_KERNEL);
909         if (tbl == NULL)
910                 return -ENOMEM;
911
912         atomic_set(&ht->nelems, 0);
913
914         RCU_INIT_POINTER(ht->tbl, tbl);
915
916         INIT_WORK(&ht->run_work, rht_deferred_worker);
917
918         return 0;
919 }
920 EXPORT_SYMBOL_GPL(rhashtable_init);
921
922 /**
923  * rhltable_init - initialize a new hash list table
924  * @hlt:        hash list table to be initialized
925  * @params:     configuration parameters
926  *
927  * Initializes a new hash list table.
928  *
929  * See documentation for rhashtable_init.
930  */
931 int rhltable_init(struct rhltable *hlt, const struct rhashtable_params *params)
932 {
933         int err;
934
935         /* No rhlist NULLs marking for now. */
936         if (params->nulls_base)
937                 return -EINVAL;
938
939         err = rhashtable_init(&hlt->ht, params);
940         hlt->ht.rhlist = true;
941         return err;
942 }
943 EXPORT_SYMBOL_GPL(rhltable_init);
944
945 static void rhashtable_free_one(struct rhashtable *ht, struct rhash_head *obj,
946                                 void (*free_fn)(void *ptr, void *arg),
947                                 void *arg)
948 {
949         struct rhlist_head *list;
950
951         if (!ht->rhlist) {
952                 free_fn(rht_obj(ht, obj), arg);
953                 return;
954         }
955
956         list = container_of(obj, struct rhlist_head, rhead);
957         do {
958                 obj = &list->rhead;
959                 list = rht_dereference(list->next, ht);
960                 free_fn(rht_obj(ht, obj), arg);
961         } while (list);
962 }
963
964 /**
965  * rhashtable_free_and_destroy - free elements and destroy hash table
966  * @ht:         the hash table to destroy
967  * @free_fn:    callback to release resources of element
968  * @arg:        pointer passed to free_fn
969  *
970  * Stops an eventual async resize. If defined, invokes free_fn for each
971  * element to releasal resources. Please note that RCU protected
972  * readers may still be accessing the elements. Releasing of resources
973  * must occur in a compatible manner. Then frees the bucket array.
974  *
975  * This function will eventually sleep to wait for an async resize
976  * to complete. The caller is responsible that no further write operations
977  * occurs in parallel.
978  */
979 void rhashtable_free_and_destroy(struct rhashtable *ht,
980                                  void (*free_fn)(void *ptr, void *arg),
981                                  void *arg)
982 {
983         const struct bucket_table *tbl;
984         unsigned int i;
985
986         cancel_work_sync(&ht->run_work);
987
988         mutex_lock(&ht->mutex);
989         tbl = rht_dereference(ht->tbl, ht);
990         if (free_fn) {
991                 for (i = 0; i < tbl->size; i++) {
992                         struct rhash_head *pos, *next;
993
994                         for (pos = rht_dereference(tbl->buckets[i], ht),
995                              next = !rht_is_a_nulls(pos) ?
996                                         rht_dereference(pos->next, ht) : NULL;
997                              !rht_is_a_nulls(pos);
998                              pos = next,
999                              next = !rht_is_a_nulls(pos) ?
1000                                         rht_dereference(pos->next, ht) : NULL)
1001                                 rhashtable_free_one(ht, pos, free_fn, arg);
1002                 }
1003         }
1004
1005         bucket_table_free(tbl);
1006         mutex_unlock(&ht->mutex);
1007 }
1008 EXPORT_SYMBOL_GPL(rhashtable_free_and_destroy);
1009
1010 void rhashtable_destroy(struct rhashtable *ht)
1011 {
1012         return rhashtable_free_and_destroy(ht, NULL, NULL);
1013 }
1014 EXPORT_SYMBOL_GPL(rhashtable_destroy);
1015 #endif