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