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