]> git.sesse.net Git - bcachefs-tools-debian/blob - include/linux/rhashtable.h
Update bcachefs sources to fb39031ade bcachefs: bch2_sb_maybe_downgrade(), bch2_sb_up...
[bcachefs-tools-debian] / include / linux / rhashtable.h
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * Resizable, Scalable, Concurrent Hash Table
4  *
5  * Copyright (c) 2015-2016 Herbert Xu <herbert@gondor.apana.org.au>
6  * Copyright (c) 2014-2015 Thomas Graf <tgraf@suug.ch>
7  * Copyright (c) 2008-2014 Patrick McHardy <kaber@trash.net>
8  *
9  * Code partially derived from nft_hash
10  * Rewritten with rehash code from br_multicast plus single list
11  * pointer as suggested by Josh Triplett
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License version 2 as
15  * published by the Free Software Foundation.
16  */
17
18 #ifndef _LINUX_RHASHTABLE_H
19 #define _LINUX_RHASHTABLE_H
20
21 #include <linux/err.h>
22 #include <linux/errno.h>
23 #include <linux/jhash.h>
24 #include <linux/list_nulls.h>
25 #include <linux/rcupdate.h>
26 #include <linux/workqueue.h>
27 #include <linux/rculist.h>
28 #include <linux/bit_spinlock.h>
29
30 #define BIT(nr)                 (1UL << (nr))
31
32 #include <linux/rhashtable-types.h>
33 /*
34  * Objects in an rhashtable have an embedded struct rhash_head
35  * which is linked into as hash chain from the hash table - or one
36  * of two or more hash tables when the rhashtable is being resized.
37  * The end of the chain is marked with a special nulls marks which has
38  * the least significant bit set but otherwise stores the address of
39  * the hash bucket.  This allows us to be sure we've found the end
40  * of the right list.
41  * The value stored in the hash bucket has BIT(0) used as a lock bit.
42  * This bit must be atomically set before any changes are made to
43  * the chain.  To avoid dereferencing this pointer without clearing
44  * the bit first, we use an opaque 'struct rhash_lock_head *' for the
45  * pointer stored in the bucket.  This struct needs to be defined so
46  * that rcu_dereference() works on it, but it has no content so a
47  * cast is needed for it to be useful.  This ensures it isn't
48  * used by mistake with clearing the lock bit first.
49  */
50 struct rhash_lock_head {};
51
52 /* Maximum chain length before rehash
53  *
54  * The maximum (not average) chain length grows with the size of the hash
55  * table, at a rate of (log N)/(log log N).
56  *
57  * The value of 16 is selected so that even if the hash table grew to
58  * 2^32 you would not expect the maximum chain length to exceed it
59  * unless we are under attack (or extremely unlucky).
60  *
61  * As this limit is only to detect attacks, we don't need to set it to a
62  * lower value as you'd need the chain length to vastly exceed 16 to have
63  * any real effect on the system.
64  */
65 #define RHT_ELASTICITY  16u
66
67 /**
68  * struct bucket_table - Table of hash buckets
69  * @size: Number of hash buckets
70  * @nest: Number of bits of first-level nested table.
71  * @rehash: Current bucket being rehashed
72  * @hash_rnd: Random seed to fold into hash
73  * @walkers: List of active walkers
74  * @rcu: RCU structure for freeing the table
75  * @future_tbl: Table under construction during rehashing
76  * @ntbl: Nested table used when out of memory.
77  * @buckets: size * hash buckets
78  */
79 struct bucket_table {
80         unsigned int            size;
81         unsigned int            nest;
82         u32                     hash_rnd;
83         struct list_head        walkers;
84         struct rcu_head         rcu;
85
86         struct bucket_table __rcu *future_tbl;
87
88         struct rhash_lock_head __rcu *buckets[] ____cacheline_aligned_in_smp;
89 };
90
91 /*
92  * NULLS_MARKER() expects a hash value with the low
93  * bits mostly likely to be significant, and it discards
94  * the msb.
95  * We give it an address, in which the bottom bit is
96  * always 0, and the msb might be significant.
97  * So we shift the address down one bit to align with
98  * expectations and avoid losing a significant bit.
99  *
100  * We never store the NULLS_MARKER in the hash table
101  * itself as we need the lsb for locking.
102  * Instead we store a NULL
103  */
104 #define RHT_NULLS_MARKER(ptr)   \
105         ((void *)NULLS_MARKER(((unsigned long) (ptr)) >> 1))
106 #define INIT_RHT_NULLS_HEAD(ptr)        \
107         ((ptr) = NULL)
108
109 static inline bool rht_is_a_nulls(const struct rhash_head *ptr)
110 {
111         return ((unsigned long) ptr & 1);
112 }
113
114 static inline void *rht_obj(const struct rhashtable *ht,
115                             const struct rhash_head *he)
116 {
117         return (char *)he - ht->p.head_offset;
118 }
119
120 static inline unsigned int rht_bucket_index(const struct bucket_table *tbl,
121                                             unsigned int hash)
122 {
123         return hash & (tbl->size - 1);
124 }
125
126 static inline unsigned int rht_key_get_hash(struct rhashtable *ht,
127         const void *key, const struct rhashtable_params params,
128         unsigned int hash_rnd)
129 {
130         unsigned int hash;
131
132         /* params must be equal to ht->p if it isn't constant. */
133         if (!__builtin_constant_p(params.key_len))
134                 hash = ht->p.hashfn(key, ht->key_len, hash_rnd);
135         else if (params.key_len) {
136                 unsigned int key_len = params.key_len;
137
138                 if (params.hashfn)
139                         hash = params.hashfn(key, key_len, hash_rnd);
140                 else if (key_len & (sizeof(u32) - 1))
141                         hash = jhash(key, key_len, hash_rnd);
142                 else
143                         hash = jhash2(key, key_len / sizeof(u32), hash_rnd);
144         } else {
145                 unsigned int key_len = ht->p.key_len;
146
147                 if (params.hashfn)
148                         hash = params.hashfn(key, key_len, hash_rnd);
149                 else
150                         hash = jhash(key, key_len, hash_rnd);
151         }
152
153         return hash;
154 }
155
156 static inline unsigned int rht_key_hashfn(
157         struct rhashtable *ht, const struct bucket_table *tbl,
158         const void *key, const struct rhashtable_params params)
159 {
160         unsigned int hash = rht_key_get_hash(ht, key, params, tbl->hash_rnd);
161
162         return rht_bucket_index(tbl, hash);
163 }
164
165 static inline unsigned int rht_head_hashfn(
166         struct rhashtable *ht, const struct bucket_table *tbl,
167         const struct rhash_head *he, const struct rhashtable_params params)
168 {
169         const char *ptr = rht_obj(ht, he);
170
171         return likely(params.obj_hashfn) ?
172                rht_bucket_index(tbl, params.obj_hashfn(ptr, params.key_len ?:
173                                                             ht->p.key_len,
174                                                        tbl->hash_rnd)) :
175                rht_key_hashfn(ht, tbl, ptr + params.key_offset, params);
176 }
177
178 /**
179  * rht_grow_above_75 - returns true if nelems > 0.75 * table-size
180  * @ht:         hash table
181  * @tbl:        current table
182  */
183 static inline bool rht_grow_above_75(const struct rhashtable *ht,
184                                      const struct bucket_table *tbl)
185 {
186         /* Expand table when exceeding 75% load */
187         return atomic_read(&ht->nelems) > (tbl->size / 4 * 3) &&
188                (!ht->p.max_size || tbl->size < ht->p.max_size);
189 }
190
191 /**
192  * rht_shrink_below_30 - returns true if nelems < 0.3 * table-size
193  * @ht:         hash table
194  * @tbl:        current table
195  */
196 static inline bool rht_shrink_below_30(const struct rhashtable *ht,
197                                        const struct bucket_table *tbl)
198 {
199         /* Shrink table beneath 30% load */
200         return atomic_read(&ht->nelems) < (tbl->size * 3 / 10) &&
201                tbl->size > ht->p.min_size;
202 }
203
204 /**
205  * rht_grow_above_100 - returns true if nelems > table-size
206  * @ht:         hash table
207  * @tbl:        current table
208  */
209 static inline bool rht_grow_above_100(const struct rhashtable *ht,
210                                       const struct bucket_table *tbl)
211 {
212         return atomic_read(&ht->nelems) > tbl->size &&
213                 (!ht->p.max_size || tbl->size < ht->p.max_size);
214 }
215
216 /**
217  * rht_grow_above_max - returns true if table is above maximum
218  * @ht:         hash table
219  * @tbl:        current table
220  */
221 static inline bool rht_grow_above_max(const struct rhashtable *ht,
222                                       const struct bucket_table *tbl)
223 {
224         return atomic_read(&ht->nelems) >= ht->max_elems;
225 }
226
227 #ifdef CONFIG_PROVE_LOCKING
228 int lockdep_rht_mutex_is_held(struct rhashtable *ht);
229 int lockdep_rht_bucket_is_held(const struct bucket_table *tbl, u32 hash);
230 #else
231 static inline int lockdep_rht_mutex_is_held(struct rhashtable *ht)
232 {
233         return 1;
234 }
235
236 static inline int lockdep_rht_bucket_is_held(const struct bucket_table *tbl,
237                                              u32 hash)
238 {
239         return 1;
240 }
241 #endif /* CONFIG_PROVE_LOCKING */
242
243 void *rhashtable_insert_slow(struct rhashtable *ht, const void *key,
244                              struct rhash_head *obj);
245
246 void rhashtable_walk_enter(struct rhashtable *ht,
247                            struct rhashtable_iter *iter);
248 void rhashtable_walk_exit(struct rhashtable_iter *iter);
249 int rhashtable_walk_start_check(struct rhashtable_iter *iter) __acquires(RCU);
250
251 static inline void rhashtable_walk_start(struct rhashtable_iter *iter)
252 {
253         (void)rhashtable_walk_start_check(iter);
254 }
255
256 void *rhashtable_walk_next(struct rhashtable_iter *iter);
257 void *rhashtable_walk_peek(struct rhashtable_iter *iter);
258 void rhashtable_walk_stop(struct rhashtable_iter *iter) __releases(RCU);
259
260 void rhashtable_free_and_destroy(struct rhashtable *ht,
261                                  void (*free_fn)(void *ptr, void *arg),
262                                  void *arg);
263 void rhashtable_destroy(struct rhashtable *ht);
264
265 struct rhash_lock_head __rcu **rht_bucket_nested(
266         const struct bucket_table *tbl, unsigned int hash);
267 struct rhash_lock_head __rcu **__rht_bucket_nested(
268         const struct bucket_table *tbl, unsigned int hash);
269 struct rhash_lock_head __rcu **rht_bucket_nested_insert(
270         struct rhashtable *ht, struct bucket_table *tbl, unsigned int hash);
271
272 #define rht_dereference(p, ht) \
273         rcu_dereference(p)
274
275 #define rht_dereference_rcu(p, ht) \
276         rcu_dereference(p)
277
278 #define rht_dereference_bucket(p, tbl, hash) \
279         rcu_dereference(p)
280
281 #define rht_dereference_bucket_rcu(p, tbl, hash) \
282         rcu_dereference(p)
283
284 #define rht_entry(tpos, pos, member) \
285         ({ tpos = container_of(pos, typeof(*tpos), member); 1; })
286
287 static inline struct rhash_lock_head __rcu *const *rht_bucket(
288         const struct bucket_table *tbl, unsigned int hash)
289 {
290         return unlikely(tbl->nest) ? rht_bucket_nested(tbl, hash) :
291                                      &tbl->buckets[hash];
292 }
293
294 static inline struct rhash_lock_head __rcu **rht_bucket_var(
295         struct bucket_table *tbl, unsigned int hash)
296 {
297         return unlikely(tbl->nest) ? __rht_bucket_nested(tbl, hash) :
298                                      &tbl->buckets[hash];
299 }
300
301 static inline struct rhash_lock_head __rcu **rht_bucket_insert(
302         struct rhashtable *ht, struct bucket_table *tbl, unsigned int hash)
303 {
304         return unlikely(tbl->nest) ? rht_bucket_nested_insert(ht, tbl, hash) :
305                                      &tbl->buckets[hash];
306 }
307
308 /*
309  * We lock a bucket by setting BIT(0) in the pointer - this is always
310  * zero in real pointers.  The NULLS mark is never stored in the bucket,
311  * rather we store NULL if the bucket is empty.
312  * bit_spin_locks do not handle contention well, but the whole point
313  * of the hashtable design is to achieve minimum per-bucket contention.
314  * A nested hash table might not have a bucket pointer.  In that case
315  * we cannot get a lock.  For remove and replace the bucket cannot be
316  * interesting and doesn't need locking.
317  * For insert we allocate the bucket if this is the last bucket_table,
318  * and then take the lock.
319  * Sometimes we unlock a bucket by writing a new pointer there.  In that
320  * case we don't need to unlock, but we do need to reset state such as
321  * local_bh. For that we have rht_assign_unlock().  As rcu_assign_pointer()
322  * provides the same release semantics that bit_spin_unlock() provides,
323  * this is safe.
324  * When we write to a bucket without unlocking, we use rht_assign_locked().
325  */
326
327 static inline void rht_lock(struct bucket_table *tbl,
328                             struct rhash_lock_head __rcu **bkt)
329 {
330         bit_spin_lock(0, (unsigned long *)bkt);
331 }
332
333 static inline void rht_lock_nested(struct bucket_table *tbl,
334                                    struct rhash_lock_head __rcu **bucket,
335                                    unsigned int subclass)
336 {
337         bit_spin_lock(0, (unsigned long *)bucket);
338 }
339
340 static inline void rht_unlock(struct bucket_table *tbl,
341                               struct rhash_lock_head __rcu **bkt)
342 {
343         bit_spin_unlock(0, (unsigned long *)bkt);
344 }
345
346 static inline struct rhash_head *__rht_ptr(
347         struct rhash_lock_head *p, struct rhash_lock_head __rcu *const *bkt)
348 {
349         return (struct rhash_head *)
350                 ((unsigned long)p & ~BIT(0) ?:
351                  (unsigned long)RHT_NULLS_MARKER(bkt));
352 }
353
354 /*
355  * Where 'bkt' is a bucket and might be locked:
356  *   rht_ptr_rcu() dereferences that pointer and clears the lock bit.
357  *   rht_ptr() dereferences in a context where the bucket is locked.
358  *   rht_ptr_exclusive() dereferences in a context where exclusive
359  *            access is guaranteed, such as when destroying the table.
360  */
361 static inline struct rhash_head *rht_ptr_rcu(
362         struct rhash_lock_head __rcu *const *bkt)
363 {
364         return __rht_ptr(rcu_dereference(*bkt), bkt);
365 }
366
367 static inline struct rhash_head *rht_ptr(
368         struct rhash_lock_head __rcu *const *bkt,
369         struct bucket_table *tbl,
370         unsigned int hash)
371 {
372         return __rht_ptr(rht_dereference_bucket(*bkt, tbl, hash), bkt);
373 }
374
375 static inline struct rhash_head *rht_ptr_exclusive(
376         struct rhash_lock_head __rcu *const *bkt)
377 {
378         return __rht_ptr(rcu_dereference(*bkt), bkt);
379 }
380
381 static inline void rht_assign_locked(struct rhash_lock_head __rcu **bkt,
382                                      struct rhash_head *obj)
383 {
384         if (rht_is_a_nulls(obj))
385                 obj = NULL;
386         rcu_assign_pointer(*bkt, (void *)((unsigned long)obj | BIT(0)));
387 }
388
389 static inline void rht_assign_unlock(struct bucket_table *tbl,
390                                      struct rhash_lock_head __rcu **bkt,
391                                      struct rhash_head *obj)
392 {
393         if (rht_is_a_nulls(obj))
394                 obj = NULL;
395         rcu_assign_pointer(*bkt, (void *)obj);
396         preempt_enable();
397         __release(bitlock);
398         bit_spin_wake(0, (unsigned long *) bkt);
399 }
400
401 /**
402  * rht_for_each_from - iterate over hash chain from given head
403  * @pos:        the &struct rhash_head to use as a loop cursor.
404  * @head:       the &struct rhash_head to start from
405  * @tbl:        the &struct bucket_table
406  * @hash:       the hash value / bucket index
407  */
408 #define rht_for_each_from(pos, head, tbl, hash) \
409         for (pos = head;                        \
410              !rht_is_a_nulls(pos);              \
411              pos = rht_dereference_bucket((pos)->next, tbl, hash))
412
413 /**
414  * rht_for_each - iterate over hash chain
415  * @pos:        the &struct rhash_head to use as a loop cursor.
416  * @tbl:        the &struct bucket_table
417  * @hash:       the hash value / bucket index
418  */
419 #define rht_for_each(pos, tbl, hash) \
420         rht_for_each_from(pos, rht_ptr(rht_bucket(tbl, hash), tbl, hash),  \
421                           tbl, hash)
422
423 /**
424  * rht_for_each_entry_from - iterate over hash chain from given head
425  * @tpos:       the type * to use as a loop cursor.
426  * @pos:        the &struct rhash_head to use as a loop cursor.
427  * @head:       the &struct rhash_head to start from
428  * @tbl:        the &struct bucket_table
429  * @hash:       the hash value / bucket index
430  * @member:     name of the &struct rhash_head within the hashable struct.
431  */
432 #define rht_for_each_entry_from(tpos, pos, head, tbl, hash, member)     \
433         for (pos = head;                                                \
434              (!rht_is_a_nulls(pos)) && rht_entry(tpos, pos, member);    \
435              pos = rht_dereference_bucket((pos)->next, tbl, hash))
436
437 /**
438  * rht_for_each_entry - iterate over hash chain of given type
439  * @tpos:       the type * to use as a loop cursor.
440  * @pos:        the &struct rhash_head to use as a loop cursor.
441  * @tbl:        the &struct bucket_table
442  * @hash:       the hash value / bucket index
443  * @member:     name of the &struct rhash_head within the hashable struct.
444  */
445 #define rht_for_each_entry(tpos, pos, tbl, hash, member)                \
446         rht_for_each_entry_from(tpos, pos,                              \
447                                 rht_ptr(rht_bucket(tbl, hash), tbl, hash), \
448                                 tbl, hash, member)
449
450 /**
451  * rht_for_each_entry_safe - safely iterate over hash chain of given type
452  * @tpos:       the type * to use as a loop cursor.
453  * @pos:        the &struct rhash_head to use as a loop cursor.
454  * @next:       the &struct rhash_head to use as next in loop cursor.
455  * @tbl:        the &struct bucket_table
456  * @hash:       the hash value / bucket index
457  * @member:     name of the &struct rhash_head within the hashable struct.
458  *
459  * This hash chain list-traversal primitive allows for the looped code to
460  * remove the loop cursor from the list.
461  */
462 #define rht_for_each_entry_safe(tpos, pos, next, tbl, hash, member)           \
463         for (pos = rht_ptr(rht_bucket(tbl, hash), tbl, hash),                 \
464              next = !rht_is_a_nulls(pos) ?                                    \
465                        rht_dereference_bucket(pos->next, tbl, hash) : NULL;   \
466              (!rht_is_a_nulls(pos)) && rht_entry(tpos, pos, member);          \
467              pos = next,                                                      \
468              next = !rht_is_a_nulls(pos) ?                                    \
469                        rht_dereference_bucket(pos->next, tbl, hash) : NULL)
470
471 /**
472  * rht_for_each_rcu_from - iterate over rcu hash chain from given head
473  * @pos:        the &struct rhash_head to use as a loop cursor.
474  * @head:       the &struct rhash_head to start from
475  * @tbl:        the &struct bucket_table
476  * @hash:       the hash value / bucket index
477  *
478  * This hash chain list-traversal primitive may safely run concurrently with
479  * the _rcu mutation primitives such as rhashtable_insert() as long as the
480  * traversal is guarded by rcu_read_lock().
481  */
482 #define rht_for_each_rcu_from(pos, head, tbl, hash)                     \
483         for (({barrier(); }),                                           \
484              pos = head;                                                \
485              !rht_is_a_nulls(pos);                                      \
486              pos = rcu_dereference_raw(pos->next))
487
488 /**
489  * rht_for_each_rcu - iterate over rcu hash chain
490  * @pos:        the &struct rhash_head to use as a loop cursor.
491  * @tbl:        the &struct bucket_table
492  * @hash:       the hash value / bucket index
493  *
494  * This hash chain list-traversal primitive may safely run concurrently with
495  * the _rcu mutation primitives such as rhashtable_insert() as long as the
496  * traversal is guarded by rcu_read_lock().
497  */
498 #define rht_for_each_rcu(pos, tbl, hash)                        \
499         for (({barrier(); }),                                   \
500              pos = rht_ptr_rcu(rht_bucket(tbl, hash));          \
501              !rht_is_a_nulls(pos);                              \
502              pos = rcu_dereference_raw(pos->next))
503
504 /**
505  * rht_for_each_entry_rcu_from - iterated over rcu hash chain from given head
506  * @tpos:       the type * to use as a loop cursor.
507  * @pos:        the &struct rhash_head to use as a loop cursor.
508  * @head:       the &struct rhash_head to start from
509  * @tbl:        the &struct bucket_table
510  * @hash:       the hash value / bucket index
511  * @member:     name of the &struct rhash_head within the hashable struct.
512  *
513  * This hash chain list-traversal primitive may safely run concurrently with
514  * the _rcu mutation primitives such as rhashtable_insert() as long as the
515  * traversal is guarded by rcu_read_lock().
516  */
517 #define rht_for_each_entry_rcu_from(tpos, pos, head, tbl, hash, member) \
518         for (({barrier(); }),                                               \
519              pos = head;                                                    \
520              (!rht_is_a_nulls(pos)) && rht_entry(tpos, pos, member);        \
521              pos = rht_dereference_bucket_rcu(pos->next, tbl, hash))
522
523 /**
524  * rht_for_each_entry_rcu - iterate over rcu hash chain of given type
525  * @tpos:       the type * to use as a loop cursor.
526  * @pos:        the &struct rhash_head to use as a loop cursor.
527  * @tbl:        the &struct bucket_table
528  * @hash:       the hash value / bucket index
529  * @member:     name of the &struct rhash_head within the hashable struct.
530  *
531  * This hash chain list-traversal primitive may safely run concurrently with
532  * the _rcu mutation primitives such as rhashtable_insert() as long as the
533  * traversal is guarded by rcu_read_lock().
534  */
535 #define rht_for_each_entry_rcu(tpos, pos, tbl, hash, member)               \
536         rht_for_each_entry_rcu_from(tpos, pos,                             \
537                                     rht_ptr_rcu(rht_bucket(tbl, hash)),    \
538                                     tbl, hash, member)
539
540 /**
541  * rhl_for_each_rcu - iterate over rcu hash table list
542  * @pos:        the &struct rlist_head to use as a loop cursor.
543  * @list:       the head of the list
544  *
545  * This hash chain list-traversal primitive should be used on the
546  * list returned by rhltable_lookup.
547  */
548 #define rhl_for_each_rcu(pos, list)                                     \
549         for (pos = list; pos; pos = rcu_dereference_raw(pos->next))
550
551 /**
552  * rhl_for_each_entry_rcu - iterate over rcu hash table list of given type
553  * @tpos:       the type * to use as a loop cursor.
554  * @pos:        the &struct rlist_head to use as a loop cursor.
555  * @list:       the head of the list
556  * @member:     name of the &struct rlist_head within the hashable struct.
557  *
558  * This hash chain list-traversal primitive should be used on the
559  * list returned by rhltable_lookup.
560  */
561 #define rhl_for_each_entry_rcu(tpos, pos, list, member)                 \
562         for (pos = list; pos && rht_entry(tpos, pos, member);           \
563              pos = rcu_dereference_raw(pos->next))
564
565 static inline int rhashtable_compare(struct rhashtable_compare_arg *arg,
566                                      const void *obj)
567 {
568         struct rhashtable *ht = arg->ht;
569         const char *ptr = obj;
570
571         return memcmp(ptr + ht->p.key_offset, arg->key, ht->p.key_len);
572 }
573
574 /* Internal function, do not use. */
575 static inline struct rhash_head *__rhashtable_lookup(
576         struct rhashtable *ht, const void *key,
577         const struct rhashtable_params params)
578 {
579         struct rhashtable_compare_arg arg = {
580                 .ht = ht,
581                 .key = key,
582         };
583         struct rhash_lock_head __rcu *const *bkt;
584         struct bucket_table *tbl;
585         struct rhash_head *he;
586         unsigned int hash;
587
588         tbl = rht_dereference_rcu(ht->tbl, ht);
589 restart:
590         hash = rht_key_hashfn(ht, tbl, key, params);
591         bkt = rht_bucket(tbl, hash);
592         do {
593                 rht_for_each_rcu_from(he, rht_ptr_rcu(bkt), tbl, hash) {
594                         if (params.obj_cmpfn ?
595                             params.obj_cmpfn(&arg, rht_obj(ht, he)) :
596                             rhashtable_compare(&arg, rht_obj(ht, he)))
597                                 continue;
598                         return he;
599                 }
600                 /* An object might have been moved to a different hash chain,
601                  * while we walk along it - better check and retry.
602                  */
603         } while (he != RHT_NULLS_MARKER(bkt));
604
605         /* Ensure we see any new tables. */
606         smp_rmb();
607
608         tbl = rht_dereference_rcu(tbl->future_tbl, ht);
609         if (unlikely(tbl))
610                 goto restart;
611
612         return NULL;
613 }
614
615 /**
616  * rhashtable_lookup - search hash table
617  * @ht:         hash table
618  * @key:        the pointer to the key
619  * @params:     hash table parameters
620  *
621  * Computes the hash value for the key and traverses the bucket chain looking
622  * for a entry with an identical key. The first matching entry is returned.
623  *
624  * This must only be called under the RCU read lock.
625  *
626  * Returns the first entry on which the compare function returned true.
627  */
628 static inline void *rhashtable_lookup(
629         struct rhashtable *ht, const void *key,
630         const struct rhashtable_params params)
631 {
632         struct rhash_head *he = __rhashtable_lookup(ht, key, params);
633
634         return he ? rht_obj(ht, he) : NULL;
635 }
636
637 /**
638  * rhashtable_lookup_fast - search hash table, without RCU read lock
639  * @ht:         hash table
640  * @key:        the pointer to the key
641  * @params:     hash table parameters
642  *
643  * Computes the hash value for the key and traverses the bucket chain looking
644  * for a entry with an identical key. The first matching entry is returned.
645  *
646  * Only use this function when you have other mechanisms guaranteeing
647  * that the object won't go away after the RCU read lock is released.
648  *
649  * Returns the first entry on which the compare function returned true.
650  */
651 static inline void *rhashtable_lookup_fast(
652         struct rhashtable *ht, const void *key,
653         const struct rhashtable_params params)
654 {
655         void *obj;
656
657         rcu_read_lock();
658         obj = rhashtable_lookup(ht, key, params);
659         rcu_read_unlock();
660
661         return obj;
662 }
663
664 /**
665  * rhltable_lookup - search hash list table
666  * @hlt:        hash table
667  * @key:        the pointer to the key
668  * @params:     hash table parameters
669  *
670  * Computes the hash value for the key and traverses the bucket chain looking
671  * for a entry with an identical key.  All matching entries are returned
672  * in a list.
673  *
674  * This must only be called under the RCU read lock.
675  *
676  * Returns the list of entries that match the given key.
677  */
678 static inline struct rhlist_head *rhltable_lookup(
679         struct rhltable *hlt, const void *key,
680         const struct rhashtable_params params)
681 {
682         struct rhash_head *he = __rhashtable_lookup(&hlt->ht, key, params);
683
684         return he ? container_of(he, struct rhlist_head, rhead) : NULL;
685 }
686
687 /* Internal function, please use rhashtable_insert_fast() instead. This
688  * function returns the existing element already in hashes in there is a clash,
689  * otherwise it returns an error via ERR_PTR().
690  */
691 static inline void *__rhashtable_insert_fast(
692         struct rhashtable *ht, const void *key, struct rhash_head *obj,
693         const struct rhashtable_params params, bool rhlist)
694 {
695         struct rhashtable_compare_arg arg = {
696                 .ht = ht,
697                 .key = key,
698         };
699         struct rhash_lock_head __rcu **bkt;
700         struct rhash_head __rcu **pprev;
701         struct bucket_table *tbl;
702         struct rhash_head *head;
703         unsigned int hash;
704         int elasticity;
705         void *data;
706
707         rcu_read_lock();
708
709         tbl = rht_dereference_rcu(ht->tbl, ht);
710         hash = rht_head_hashfn(ht, tbl, obj, params);
711         elasticity = RHT_ELASTICITY;
712         bkt = rht_bucket_insert(ht, tbl, hash);
713         data = ERR_PTR(-ENOMEM);
714         if (!bkt)
715                 goto out;
716         pprev = NULL;
717         rht_lock(tbl, bkt);
718
719         if (unlikely(rcu_access_pointer(tbl->future_tbl))) {
720 slow_path:
721                 rht_unlock(tbl, bkt);
722                 rcu_read_unlock();
723                 return rhashtable_insert_slow(ht, key, obj);
724         }
725
726         rht_for_each_from(head, rht_ptr(bkt, tbl, hash), tbl, hash) {
727                 struct rhlist_head *plist;
728                 struct rhlist_head *list;
729
730                 elasticity--;
731                 if (!key ||
732                     (params.obj_cmpfn ?
733                      params.obj_cmpfn(&arg, rht_obj(ht, head)) :
734                      rhashtable_compare(&arg, rht_obj(ht, head)))) {
735                         pprev = &head->next;
736                         continue;
737                 }
738
739                 data = rht_obj(ht, head);
740
741                 if (!rhlist)
742                         goto out_unlock;
743
744
745                 list = container_of(obj, struct rhlist_head, rhead);
746                 plist = container_of(head, struct rhlist_head, rhead);
747
748                 RCU_INIT_POINTER(list->next, plist);
749                 head = rht_dereference_bucket(head->next, tbl, hash);
750                 RCU_INIT_POINTER(list->rhead.next, head);
751                 if (pprev) {
752                         rcu_assign_pointer(*pprev, obj);
753                         rht_unlock(tbl, bkt);
754                 } else
755                         rht_assign_unlock(tbl, bkt, obj);
756                 data = NULL;
757                 goto out;
758         }
759
760         if (elasticity <= 0)
761                 goto slow_path;
762
763         data = ERR_PTR(-E2BIG);
764         if (unlikely(rht_grow_above_max(ht, tbl)))
765                 goto out_unlock;
766
767         if (unlikely(rht_grow_above_100(ht, tbl)))
768                 goto slow_path;
769
770         /* Inserting at head of list makes unlocking free. */
771         head = rht_ptr(bkt, tbl, hash);
772
773         RCU_INIT_POINTER(obj->next, head);
774         if (rhlist) {
775                 struct rhlist_head *list;
776
777                 list = container_of(obj, struct rhlist_head, rhead);
778                 RCU_INIT_POINTER(list->next, NULL);
779         }
780
781         atomic_inc(&ht->nelems);
782         rht_assign_unlock(tbl, bkt, obj);
783
784         if (rht_grow_above_75(ht, tbl))
785                 schedule_work(&ht->run_work);
786
787         data = NULL;
788 out:
789         rcu_read_unlock();
790
791         return data;
792
793 out_unlock:
794         rht_unlock(tbl, bkt);
795         goto out;
796 }
797
798 /**
799  * rhashtable_insert_fast - insert object into hash table
800  * @ht:         hash table
801  * @obj:        pointer to hash head inside object
802  * @params:     hash table parameters
803  *
804  * Will take the per bucket bitlock to protect against mutual mutations
805  * on the same bucket. Multiple insertions may occur in parallel unless
806  * they map to the same bucket.
807  *
808  * It is safe to call this function from atomic context.
809  *
810  * Will trigger an automatic deferred table resizing if residency in the
811  * table grows beyond 70%.
812  */
813 static inline int rhashtable_insert_fast(
814         struct rhashtable *ht, struct rhash_head *obj,
815         const struct rhashtable_params params)
816 {
817         void *ret;
818
819         ret = __rhashtable_insert_fast(ht, NULL, obj, params, false);
820         if (IS_ERR(ret))
821                 return PTR_ERR(ret);
822
823         return ret == NULL ? 0 : -EEXIST;
824 }
825
826 /**
827  * rhltable_insert_key - insert object into hash list table
828  * @hlt:        hash list table
829  * @key:        the pointer to the key
830  * @list:       pointer to hash list head inside object
831  * @params:     hash table parameters
832  *
833  * Will take the per bucket bitlock to protect against mutual mutations
834  * on the same bucket. Multiple insertions may occur in parallel unless
835  * they map to the same bucket.
836  *
837  * It is safe to call this function from atomic context.
838  *
839  * Will trigger an automatic deferred table resizing if residency in the
840  * table grows beyond 70%.
841  */
842 static inline int rhltable_insert_key(
843         struct rhltable *hlt, const void *key, struct rhlist_head *list,
844         const struct rhashtable_params params)
845 {
846         return PTR_ERR(__rhashtable_insert_fast(&hlt->ht, key, &list->rhead,
847                                                 params, true));
848 }
849
850 /**
851  * rhltable_insert - insert object into hash list table
852  * @hlt:        hash list table
853  * @list:       pointer to hash list head inside object
854  * @params:     hash table parameters
855  *
856  * Will take the per bucket bitlock to protect against mutual mutations
857  * on the same bucket. Multiple insertions may occur in parallel unless
858  * they map to the same bucket.
859  *
860  * It is safe to call this function from atomic context.
861  *
862  * Will trigger an automatic deferred table resizing if residency in the
863  * table grows beyond 70%.
864  */
865 static inline int rhltable_insert(
866         struct rhltable *hlt, struct rhlist_head *list,
867         const struct rhashtable_params params)
868 {
869         const char *key = rht_obj(&hlt->ht, &list->rhead);
870
871         key += params.key_offset;
872
873         return rhltable_insert_key(hlt, key, list, params);
874 }
875
876 /**
877  * rhashtable_lookup_insert_fast - lookup and insert object into hash table
878  * @ht:         hash table
879  * @obj:        pointer to hash head inside object
880  * @params:     hash table parameters
881  *
882  * This lookup function may only be used for fixed key hash table (key_len
883  * parameter set). It will BUG() if used inappropriately.
884  *
885  * It is safe to call this function from atomic context.
886  *
887  * Will trigger an automatic deferred table resizing if residency in the
888  * table grows beyond 70%.
889  */
890 static inline int rhashtable_lookup_insert_fast(
891         struct rhashtable *ht, struct rhash_head *obj,
892         const struct rhashtable_params params)
893 {
894         const char *key = rht_obj(ht, obj);
895         void *ret;
896
897         BUG_ON(ht->p.obj_hashfn);
898
899         ret = __rhashtable_insert_fast(ht, key + ht->p.key_offset, obj, params,
900                                        false);
901         if (IS_ERR(ret))
902                 return PTR_ERR(ret);
903
904         return ret == NULL ? 0 : -EEXIST;
905 }
906
907 /**
908  * rhashtable_lookup_get_insert_fast - lookup and insert object into hash table
909  * @ht:         hash table
910  * @obj:        pointer to hash head inside object
911  * @params:     hash table parameters
912  *
913  * Just like rhashtable_lookup_insert_fast(), but this function returns the
914  * object if it exists, NULL if it did not and the insertion was successful,
915  * and an ERR_PTR otherwise.
916  */
917 static inline void *rhashtable_lookup_get_insert_fast(
918         struct rhashtable *ht, struct rhash_head *obj,
919         const struct rhashtable_params params)
920 {
921         const char *key = rht_obj(ht, obj);
922
923         BUG_ON(ht->p.obj_hashfn);
924
925         return __rhashtable_insert_fast(ht, key + ht->p.key_offset, obj, params,
926                                         false);
927 }
928
929 /**
930  * rhashtable_lookup_insert_key - search and insert object to hash table
931  *                                with explicit key
932  * @ht:         hash table
933  * @key:        key
934  * @obj:        pointer to hash head inside object
935  * @params:     hash table parameters
936  *
937  * Lookups may occur in parallel with hashtable mutations and resizing.
938  *
939  * Will trigger an automatic deferred table resizing if residency in the
940  * table grows beyond 70%.
941  *
942  * Returns zero on success.
943  */
944 static inline int rhashtable_lookup_insert_key(
945         struct rhashtable *ht, const void *key, struct rhash_head *obj,
946         const struct rhashtable_params params)
947 {
948         void *ret;
949
950         BUG_ON(!ht->p.obj_hashfn || !key);
951
952         ret = __rhashtable_insert_fast(ht, key, obj, params, false);
953         if (IS_ERR(ret))
954                 return PTR_ERR(ret);
955
956         return ret == NULL ? 0 : -EEXIST;
957 }
958
959 /**
960  * rhashtable_lookup_get_insert_key - lookup and insert object into hash table
961  * @ht:         hash table
962  * @key:        key
963  * @obj:        pointer to hash head inside object
964  * @params:     hash table parameters
965  *
966  * Just like rhashtable_lookup_insert_key(), but this function returns the
967  * object if it exists, NULL if it does not and the insertion was successful,
968  * and an ERR_PTR otherwise.
969  */
970 static inline void *rhashtable_lookup_get_insert_key(
971         struct rhashtable *ht, const void *key, struct rhash_head *obj,
972         const struct rhashtable_params params)
973 {
974         BUG_ON(!ht->p.obj_hashfn || !key);
975
976         return __rhashtable_insert_fast(ht, key, obj, params, false);
977 }
978
979 /* Internal function, please use rhashtable_remove_fast() instead */
980 static inline int __rhashtable_remove_fast_one(
981         struct rhashtable *ht, struct bucket_table *tbl,
982         struct rhash_head *obj, const struct rhashtable_params params,
983         bool rhlist)
984 {
985         struct rhash_lock_head __rcu **bkt;
986         struct rhash_head __rcu **pprev;
987         struct rhash_head *he;
988         unsigned int hash;
989         int err = -ENOENT;
990
991         hash = rht_head_hashfn(ht, tbl, obj, params);
992         bkt = rht_bucket_var(tbl, hash);
993         if (!bkt)
994                 return -ENOENT;
995         pprev = NULL;
996         rht_lock(tbl, bkt);
997
998         rht_for_each_from(he, rht_ptr(bkt, tbl, hash), tbl, hash) {
999                 struct rhlist_head *list;
1000
1001                 list = container_of(he, struct rhlist_head, rhead);
1002
1003                 if (he != obj) {
1004                         struct rhlist_head __rcu **lpprev;
1005
1006                         pprev = &he->next;
1007
1008                         if (!rhlist)
1009                                 continue;
1010
1011                         do {
1012                                 lpprev = &list->next;
1013                                 list = rht_dereference_bucket(list->next,
1014                                                               tbl, hash);
1015                         } while (list && obj != &list->rhead);
1016
1017                         if (!list)
1018                                 continue;
1019
1020                         list = rht_dereference_bucket(list->next, tbl, hash);
1021                         RCU_INIT_POINTER(*lpprev, list);
1022                         err = 0;
1023                         break;
1024                 }
1025
1026                 obj = rht_dereference_bucket(obj->next, tbl, hash);
1027                 err = 1;
1028
1029                 if (rhlist) {
1030                         list = rht_dereference_bucket(list->next, tbl, hash);
1031                         if (list) {
1032                                 RCU_INIT_POINTER(list->rhead.next, obj);
1033                                 obj = &list->rhead;
1034                                 err = 0;
1035                         }
1036                 }
1037
1038                 if (pprev) {
1039                         rcu_assign_pointer(*pprev, obj);
1040                         rht_unlock(tbl, bkt);
1041                 } else {
1042                         rht_assign_unlock(tbl, bkt, obj);
1043                 }
1044                 goto unlocked;
1045         }
1046
1047         rht_unlock(tbl, bkt);
1048 unlocked:
1049         if (err > 0) {
1050                 atomic_dec(&ht->nelems);
1051                 if (unlikely(ht->p.automatic_shrinking &&
1052                              rht_shrink_below_30(ht, tbl)))
1053                         schedule_work(&ht->run_work);
1054                 err = 0;
1055         }
1056
1057         return err;
1058 }
1059
1060 /* Internal function, please use rhashtable_remove_fast() instead */
1061 static inline int __rhashtable_remove_fast(
1062         struct rhashtable *ht, struct rhash_head *obj,
1063         const struct rhashtable_params params, bool rhlist)
1064 {
1065         struct bucket_table *tbl;
1066         int err;
1067
1068         rcu_read_lock();
1069
1070         tbl = rht_dereference_rcu(ht->tbl, ht);
1071
1072         /* Because we have already taken (and released) the bucket
1073          * lock in old_tbl, if we find that future_tbl is not yet
1074          * visible then that guarantees the entry to still be in
1075          * the old tbl if it exists.
1076          */
1077         while ((err = __rhashtable_remove_fast_one(ht, tbl, obj, params,
1078                                                    rhlist)) &&
1079                (tbl = rht_dereference_rcu(tbl->future_tbl, ht)))
1080                 ;
1081
1082         rcu_read_unlock();
1083
1084         return err;
1085 }
1086
1087 /**
1088  * rhashtable_remove_fast - remove object from hash table
1089  * @ht:         hash table
1090  * @obj:        pointer to hash head inside object
1091  * @params:     hash table parameters
1092  *
1093  * Since the hash chain is single linked, the removal operation needs to
1094  * walk the bucket chain upon removal. The removal operation is thus
1095  * considerable slow if the hash table is not correctly sized.
1096  *
1097  * Will automatically shrink the table if permitted when residency drops
1098  * below 30%.
1099  *
1100  * Returns zero on success, -ENOENT if the entry could not be found.
1101  */
1102 static inline int rhashtable_remove_fast(
1103         struct rhashtable *ht, struct rhash_head *obj,
1104         const struct rhashtable_params params)
1105 {
1106         return __rhashtable_remove_fast(ht, obj, params, false);
1107 }
1108
1109 /**
1110  * rhltable_remove - remove object from hash list table
1111  * @hlt:        hash list table
1112  * @list:       pointer to hash list head inside object
1113  * @params:     hash table parameters
1114  *
1115  * Since the hash chain is single linked, the removal operation needs to
1116  * walk the bucket chain upon removal. The removal operation is thus
1117  * considerable slow if the hash table is not correctly sized.
1118  *
1119  * Will automatically shrink the table if permitted when residency drops
1120  * below 30%
1121  *
1122  * Returns zero on success, -ENOENT if the entry could not be found.
1123  */
1124 static inline int rhltable_remove(
1125         struct rhltable *hlt, struct rhlist_head *list,
1126         const struct rhashtable_params params)
1127 {
1128         return __rhashtable_remove_fast(&hlt->ht, &list->rhead, params, true);
1129 }
1130
1131 /* Internal function, please use rhashtable_replace_fast() instead */
1132 static inline int __rhashtable_replace_fast(
1133         struct rhashtable *ht, struct bucket_table *tbl,
1134         struct rhash_head *obj_old, struct rhash_head *obj_new,
1135         const struct rhashtable_params params)
1136 {
1137         struct rhash_lock_head __rcu **bkt;
1138         struct rhash_head __rcu **pprev;
1139         struct rhash_head *he;
1140         unsigned int hash;
1141         int err = -ENOENT;
1142
1143         /* Minimally, the old and new objects must have same hash
1144          * (which should mean identifiers are the same).
1145          */
1146         hash = rht_head_hashfn(ht, tbl, obj_old, params);
1147         if (hash != rht_head_hashfn(ht, tbl, obj_new, params))
1148                 return -EINVAL;
1149
1150         bkt = rht_bucket_var(tbl, hash);
1151         if (!bkt)
1152                 return -ENOENT;
1153
1154         pprev = NULL;
1155         rht_lock(tbl, bkt);
1156
1157         rht_for_each_from(he, rht_ptr(bkt, tbl, hash), tbl, hash) {
1158                 if (he != obj_old) {
1159                         pprev = &he->next;
1160                         continue;
1161                 }
1162
1163                 rcu_assign_pointer(obj_new->next, obj_old->next);
1164                 if (pprev) {
1165                         rcu_assign_pointer(*pprev, obj_new);
1166                         rht_unlock(tbl, bkt);
1167                 } else {
1168                         rht_assign_unlock(tbl, bkt, obj_new);
1169                 }
1170                 err = 0;
1171                 goto unlocked;
1172         }
1173
1174         rht_unlock(tbl, bkt);
1175
1176 unlocked:
1177         return err;
1178 }
1179
1180 /**
1181  * rhashtable_replace_fast - replace an object in hash table
1182  * @ht:         hash table
1183  * @obj_old:    pointer to hash head inside object being replaced
1184  * @obj_new:    pointer to hash head inside object which is new
1185  * @params:     hash table parameters
1186  *
1187  * Replacing an object doesn't affect the number of elements in the hash table
1188  * or bucket, so we don't need to worry about shrinking or expanding the
1189  * table here.
1190  *
1191  * Returns zero on success, -ENOENT if the entry could not be found,
1192  * -EINVAL if hash is not the same for the old and new objects.
1193  */
1194 static inline int rhashtable_replace_fast(
1195         struct rhashtable *ht, struct rhash_head *obj_old,
1196         struct rhash_head *obj_new,
1197         const struct rhashtable_params params)
1198 {
1199         struct bucket_table *tbl;
1200         int err;
1201
1202         rcu_read_lock();
1203
1204         tbl = rht_dereference_rcu(ht->tbl, ht);
1205
1206         /* Because we have already taken (and released) the bucket
1207          * lock in old_tbl, if we find that future_tbl is not yet
1208          * visible then that guarantees the entry to still be in
1209          * the old tbl if it exists.
1210          */
1211         while ((err = __rhashtable_replace_fast(ht, tbl, obj_old,
1212                                                 obj_new, params)) &&
1213                (tbl = rht_dereference_rcu(tbl->future_tbl, ht)))
1214                 ;
1215
1216         rcu_read_unlock();
1217
1218         return err;
1219 }
1220
1221 /**
1222  * rhltable_walk_enter - Initialise an iterator
1223  * @hlt:        Table to walk over
1224  * @iter:       Hash table Iterator
1225  *
1226  * This function prepares a hash table walk.
1227  *
1228  * Note that if you restart a walk after rhashtable_walk_stop you
1229  * may see the same object twice.  Also, you may miss objects if
1230  * there are removals in between rhashtable_walk_stop and the next
1231  * call to rhashtable_walk_start.
1232  *
1233  * For a completely stable walk you should construct your own data
1234  * structure outside the hash table.
1235  *
1236  * This function may be called from any process context, including
1237  * non-preemptable context, but cannot be called from softirq or
1238  * hardirq context.
1239  *
1240  * You must call rhashtable_walk_exit after this function returns.
1241  */
1242 static inline void rhltable_walk_enter(struct rhltable *hlt,
1243                                        struct rhashtable_iter *iter)
1244 {
1245         return rhashtable_walk_enter(&hlt->ht, iter);
1246 }
1247
1248 /**
1249  * rhltable_free_and_destroy - free elements and destroy hash list table
1250  * @hlt:        the hash list table to destroy
1251  * @free_fn:    callback to release resources of element
1252  * @arg:        pointer passed to free_fn
1253  *
1254  * See documentation for rhashtable_free_and_destroy.
1255  */
1256 static inline void rhltable_free_and_destroy(struct rhltable *hlt,
1257                                              void (*free_fn)(void *ptr,
1258                                                              void *arg),
1259                                              void *arg)
1260 {
1261         return rhashtable_free_and_destroy(&hlt->ht, free_fn, arg);
1262 }
1263
1264 static inline void rhltable_destroy(struct rhltable *hlt)
1265 {
1266         return rhltable_free_and_destroy(hlt, NULL, NULL);
1267 }
1268
1269 #endif /* _LINUX_RHASHTABLE_H */