]> git.sesse.net Git - bcachefs-tools-debian/blob - include/linux/rhashtable.h
e5b35edd5ee6a66da19fd69a7b79775866b1c55a
[bcachefs-tools-debian] / include / linux / rhashtable.h
1 /*
2  * Resizable, Scalable, Concurrent Hash Table
3  *
4  * Copyright (c) 2015 Herbert Xu <herbert@gondor.apana.org.au>
5  * Copyright (c) 2014-2015 Thomas Graf <tgraf@suug.ch>
6  * Copyright (c) 2008-2014 Patrick McHardy <kaber@trash.net>
7  *
8  * Code partially derived from nft_hash
9  * Rewritten with rehash code from br_multicast plus single list
10  * pointer as suggested by Josh Triplett
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License version 2 as
14  * published by the Free Software Foundation.
15  */
16
17 #ifndef _LINUX_RHASHTABLE_H
18 #define _LINUX_RHASHTABLE_H
19
20 #include <linux/atomic.h>
21 #include <linux/cache.h>
22 #include <linux/compiler.h>
23 #include <linux/cpumask.h>
24 #include <linux/err.h>
25 #include <linux/errno.h>
26 #include <linux/jhash.h>
27 #include <linux/list_nulls.h>
28 #include <linux/workqueue.h>
29 #include <linux/mutex.h>
30 #include <linux/spinlock.h>
31 #include <linux/rcupdate.h>
32
33 /*
34  * The end of the chain is marked with a special nulls marks which has
35  * the following format:
36  *
37  * +-------+-----------------------------------------------------+-+
38  * | Base  |                      Hash                           |1|
39  * +-------+-----------------------------------------------------+-+
40  *
41  * Base (4 bits) : Reserved to distinguish between multiple tables.
42  *                 Specified via &struct rhashtable_params.nulls_base.
43  * Hash (27 bits): Full hash (unmasked) of first element added to bucket
44  * 1 (1 bit)     : Nulls marker (always set)
45  *
46  * The remaining bits of the next pointer remain unused for now.
47  */
48 #define RHT_BASE_BITS           4
49 #define RHT_HASH_BITS           27
50 #define RHT_BASE_SHIFT          RHT_HASH_BITS
51
52 /* Base bits plus 1 bit for nulls marker */
53 #define RHT_HASH_RESERVED_SPACE (RHT_BASE_BITS + 1)
54
55 struct rhash_head {
56         struct rhash_head __rcu         *next;
57 };
58
59 /**
60  * struct bucket_table - Table of hash buckets
61  * @size: Number of hash buckets
62  * @rehash: Current bucket being rehashed
63  * @hash_rnd: Random seed to fold into hash
64  * @locks_mask: Mask to apply before accessing locks[]
65  * @locks: Array of spinlocks protecting individual buckets
66  * @walkers: List of active walkers
67  * @rcu: RCU structure for freeing the table
68  * @future_tbl: Table under construction during rehashing
69  * @buckets: size * hash buckets
70  */
71 struct bucket_table {
72         unsigned int            size;
73         unsigned int            rehash;
74         u32                     hash_rnd;
75         unsigned int            locks_mask;
76         spinlock_t              *locks;
77         struct list_head        walkers;
78         struct rcu_head         rcu;
79
80         struct bucket_table __rcu *future_tbl;
81
82         struct rhash_head __rcu *buckets[] ____cacheline_aligned_in_smp;
83 };
84
85 /**
86  * struct rhashtable_compare_arg - Key for the function rhashtable_compare
87  * @ht: Hash table
88  * @key: Key to compare against
89  */
90 struct rhashtable_compare_arg {
91         struct rhashtable *ht;
92         const void *key;
93 };
94
95 typedef u32 (*rht_hashfn_t)(const void *data, u32 len, u32 seed);
96 typedef u32 (*rht_obj_hashfn_t)(const void *data, u32 len, u32 seed);
97 typedef int (*rht_obj_cmpfn_t)(struct rhashtable_compare_arg *arg,
98                                const void *obj);
99
100 struct rhashtable;
101
102 /**
103  * struct rhashtable_params - Hash table construction parameters
104  * @nelem_hint: Hint on number of elements, should be 75% of desired size
105  * @key_len: Length of key
106  * @key_offset: Offset of key in struct to be hashed
107  * @head_offset: Offset of rhash_head in struct to be hashed
108  * @insecure_max_entries: Maximum number of entries (may be exceeded)
109  * @max_size: Maximum size while expanding
110  * @min_size: Minimum size while shrinking
111  * @nulls_base: Base value to generate nulls marker
112  * @insecure_elasticity: Set to true to disable chain length checks
113  * @automatic_shrinking: Enable automatic shrinking of tables
114  * @locks_mul: Number of bucket locks to allocate per cpu (default: 128)
115  * @hashfn: Hash function (default: jhash2 if !(key_len % 4), or jhash)
116  * @obj_hashfn: Function to hash object
117  * @obj_cmpfn: Function to compare key with object
118  */
119 struct rhashtable_params {
120         size_t                  nelem_hint;
121         size_t                  key_len;
122         size_t                  key_offset;
123         size_t                  head_offset;
124         unsigned int            insecure_max_entries;
125         unsigned int            max_size;
126         unsigned int            min_size;
127         u32                     nulls_base;
128         bool                    insecure_elasticity;
129         bool                    automatic_shrinking;
130         size_t                  locks_mul;
131         rht_hashfn_t            hashfn;
132         rht_obj_hashfn_t        obj_hashfn;
133         rht_obj_cmpfn_t         obj_cmpfn;
134 };
135
136 /**
137  * struct rhashtable - Hash table handle
138  * @tbl: Bucket table
139  * @nelems: Number of elements in table
140  * @key_len: Key length for hashfn
141  * @elasticity: Maximum chain length before rehash
142  * @p: Configuration parameters
143  * @run_work: Deferred worker to expand/shrink asynchronously
144  * @mutex: Mutex to protect current/future table swapping
145  * @lock: Spin lock to protect walker list
146  */
147 struct rhashtable {
148         struct bucket_table __rcu       *tbl;
149         atomic_t                        nelems;
150         unsigned int                    key_len;
151         unsigned int                    elasticity;
152         struct rhashtable_params        p;
153         struct work_struct              run_work;
154         struct mutex                    mutex;
155         spinlock_t                      lock;
156 };
157
158 /**
159  * struct rhashtable_walker - Hash table walker
160  * @list: List entry on list of walkers
161  * @tbl: The table that we were walking over
162  */
163 struct rhashtable_walker {
164         struct list_head list;
165         struct bucket_table *tbl;
166 };
167
168 /**
169  * struct rhashtable_iter - Hash table iterator, fits into netlink cb
170  * @ht: Table to iterate through
171  * @p: Current pointer
172  * @walker: Associated rhashtable walker
173  * @slot: Current slot
174  * @skip: Number of entries to skip in slot
175  */
176 struct rhashtable_iter {
177         struct rhashtable *ht;
178         struct rhash_head *p;
179         struct rhashtable_walker *walker;
180         unsigned int slot;
181         unsigned int skip;
182 };
183
184 static inline unsigned long rht_marker(const struct rhashtable *ht, u32 hash)
185 {
186         return NULLS_MARKER(ht->p.nulls_base + hash);
187 }
188
189 #define INIT_RHT_NULLS_HEAD(ptr, ht, hash) \
190         ((ptr) = (typeof(ptr)) rht_marker(ht, hash))
191
192 static inline bool rht_is_a_nulls(const struct rhash_head *ptr)
193 {
194         return ((unsigned long) ptr & 1);
195 }
196
197 static inline unsigned long rht_get_nulls_value(const struct rhash_head *ptr)
198 {
199         return ((unsigned long) ptr) >> 1;
200 }
201
202 static inline void *rht_obj(const struct rhashtable *ht,
203                             const struct rhash_head *he)
204 {
205         return (char *)he - ht->p.head_offset;
206 }
207
208 static inline unsigned int rht_bucket_index(const struct bucket_table *tbl,
209                                             unsigned int hash)
210 {
211         return (hash >> RHT_HASH_RESERVED_SPACE) & (tbl->size - 1);
212 }
213
214 static inline unsigned int rht_key_hashfn(
215         struct rhashtable *ht, const struct bucket_table *tbl,
216         const void *key, const struct rhashtable_params params)
217 {
218         unsigned int hash;
219
220         /* params must be equal to ht->p if it isn't constant. */
221         if (!__builtin_constant_p(params.key_len))
222                 hash = ht->p.hashfn(key, ht->key_len, tbl->hash_rnd);
223         else if (params.key_len) {
224                 unsigned int key_len = params.key_len;
225
226                 if (params.hashfn)
227                         hash = params.hashfn(key, key_len, tbl->hash_rnd);
228                 else if (key_len & (sizeof(u32) - 1))
229                         hash = jhash(key, key_len, tbl->hash_rnd);
230                 else
231                         hash = jhash2(key, key_len / sizeof(u32),
232                                       tbl->hash_rnd);
233         } else {
234                 unsigned int key_len = ht->p.key_len;
235
236                 if (params.hashfn)
237                         hash = params.hashfn(key, key_len, tbl->hash_rnd);
238                 else
239                         hash = jhash(key, key_len, tbl->hash_rnd);
240         }
241
242         return rht_bucket_index(tbl, hash);
243 }
244
245 static inline unsigned int rht_head_hashfn(
246         struct rhashtable *ht, const struct bucket_table *tbl,
247         const struct rhash_head *he, const struct rhashtable_params params)
248 {
249         const char *ptr = rht_obj(ht, he);
250
251         return likely(params.obj_hashfn) ?
252                rht_bucket_index(tbl, params.obj_hashfn(ptr, params.key_len ?:
253                                                             ht->p.key_len,
254                                                        tbl->hash_rnd)) :
255                rht_key_hashfn(ht, tbl, ptr + params.key_offset, params);
256 }
257
258 /**
259  * rht_grow_above_75 - returns true if nelems > 0.75 * table-size
260  * @ht:         hash table
261  * @tbl:        current table
262  */
263 static inline bool rht_grow_above_75(const struct rhashtable *ht,
264                                      const struct bucket_table *tbl)
265 {
266         /* Expand table when exceeding 75% load */
267         return atomic_read(&ht->nelems) > (tbl->size / 4 * 3) &&
268                (!ht->p.max_size || tbl->size < ht->p.max_size);
269 }
270
271 /**
272  * rht_shrink_below_30 - returns true if nelems < 0.3 * table-size
273  * @ht:         hash table
274  * @tbl:        current table
275  */
276 static inline bool rht_shrink_below_30(const struct rhashtable *ht,
277                                        const struct bucket_table *tbl)
278 {
279         /* Shrink table beneath 30% load */
280         return atomic_read(&ht->nelems) < (tbl->size * 3 / 10) &&
281                tbl->size > ht->p.min_size;
282 }
283
284 /**
285  * rht_grow_above_100 - returns true if nelems > table-size
286  * @ht:         hash table
287  * @tbl:        current table
288  */
289 static inline bool rht_grow_above_100(const struct rhashtable *ht,
290                                       const struct bucket_table *tbl)
291 {
292         return atomic_read(&ht->nelems) > tbl->size &&
293                 (!ht->p.max_size || tbl->size < ht->p.max_size);
294 }
295
296 /**
297  * rht_grow_above_max - returns true if table is above maximum
298  * @ht:         hash table
299  * @tbl:        current table
300  */
301 static inline bool rht_grow_above_max(const struct rhashtable *ht,
302                                       const struct bucket_table *tbl)
303 {
304         return ht->p.insecure_max_entries &&
305                atomic_read(&ht->nelems) >= ht->p.insecure_max_entries;
306 }
307
308 /* The bucket lock is selected based on the hash and protects mutations
309  * on a group of hash buckets.
310  *
311  * A maximum of tbl->size/2 bucket locks is allocated. This ensures that
312  * a single lock always covers both buckets which may both contains
313  * entries which link to the same bucket of the old table during resizing.
314  * This allows to simplify the locking as locking the bucket in both
315  * tables during resize always guarantee protection.
316  *
317  * IMPORTANT: When holding the bucket lock of both the old and new table
318  * during expansions and shrinking, the old bucket lock must always be
319  * acquired first.
320  */
321 static inline spinlock_t *rht_bucket_lock(const struct bucket_table *tbl,
322                                           unsigned int hash)
323 {
324         return &tbl->locks[hash & tbl->locks_mask];
325 }
326
327 #ifdef CONFIG_PROVE_LOCKING
328 int lockdep_rht_mutex_is_held(struct rhashtable *ht);
329 int lockdep_rht_bucket_is_held(const struct bucket_table *tbl, u32 hash);
330 #else
331 static inline int lockdep_rht_mutex_is_held(struct rhashtable *ht)
332 {
333         return 1;
334 }
335
336 static inline int lockdep_rht_bucket_is_held(const struct bucket_table *tbl,
337                                              u32 hash)
338 {
339         return 1;
340 }
341 #endif /* CONFIG_PROVE_LOCKING */
342
343 int rhashtable_init(struct rhashtable *ht,
344                     const struct rhashtable_params *params);
345
346 struct bucket_table *rhashtable_insert_slow(struct rhashtable *ht,
347                                             const void *key,
348                                             struct rhash_head *obj,
349                                             struct bucket_table *old_tbl);
350 int rhashtable_insert_rehash(struct rhashtable *ht, struct bucket_table *tbl);
351
352 int rhashtable_walk_init(struct rhashtable *ht, struct rhashtable_iter *iter,
353                          gfp_t gfp);
354 void rhashtable_walk_exit(struct rhashtable_iter *iter);
355 int rhashtable_walk_start(struct rhashtable_iter *iter) __acquires(RCU);
356 void *rhashtable_walk_next(struct rhashtable_iter *iter);
357 void rhashtable_walk_stop(struct rhashtable_iter *iter) __releases(RCU);
358
359 void rhashtable_free_and_destroy(struct rhashtable *ht,
360                                  void (*free_fn)(void *ptr, void *arg),
361                                  void *arg);
362 void rhashtable_destroy(struct rhashtable *ht);
363
364 #define rht_dereference(p, ht) \
365         rcu_dereference_protected(p, lockdep_rht_mutex_is_held(ht))
366
367 #define rht_dereference_rcu(p, ht) \
368         rcu_dereference_check(p, lockdep_rht_mutex_is_held(ht))
369
370 #define rht_dereference_bucket(p, tbl, hash) \
371         rcu_dereference_protected(p, lockdep_rht_bucket_is_held(tbl, hash))
372
373 #define rht_dereference_bucket_rcu(p, tbl, hash) \
374         rcu_dereference_check(p, lockdep_rht_bucket_is_held(tbl, hash))
375
376 #define rht_entry(tpos, pos, member) \
377         ({ tpos = container_of(pos, typeof(*tpos), member); 1; })
378
379 /**
380  * rht_for_each_continue - continue iterating over hash chain
381  * @pos:        the &struct rhash_head to use as a loop cursor.
382  * @head:       the previous &struct rhash_head to continue from
383  * @tbl:        the &struct bucket_table
384  * @hash:       the hash value / bucket index
385  */
386 #define rht_for_each_continue(pos, head, tbl, hash) \
387         for (pos = rht_dereference_bucket(head, tbl, hash); \
388              !rht_is_a_nulls(pos); \
389              pos = rht_dereference_bucket((pos)->next, tbl, hash))
390
391 /**
392  * rht_for_each - iterate over hash chain
393  * @pos:        the &struct rhash_head to use as a loop cursor.
394  * @tbl:        the &struct bucket_table
395  * @hash:       the hash value / bucket index
396  */
397 #define rht_for_each(pos, tbl, hash) \
398         rht_for_each_continue(pos, (tbl)->buckets[hash], tbl, hash)
399
400 /**
401  * rht_for_each_entry_continue - continue iterating over hash chain
402  * @tpos:       the type * to use as a loop cursor.
403  * @pos:        the &struct rhash_head to use as a loop cursor.
404  * @head:       the previous &struct rhash_head to continue from
405  * @tbl:        the &struct bucket_table
406  * @hash:       the hash value / bucket index
407  * @member:     name of the &struct rhash_head within the hashable struct.
408  */
409 #define rht_for_each_entry_continue(tpos, pos, head, tbl, hash, member) \
410         for (pos = rht_dereference_bucket(head, tbl, hash);             \
411              (!rht_is_a_nulls(pos)) && rht_entry(tpos, pos, member);    \
412              pos = rht_dereference_bucket((pos)->next, tbl, hash))
413
414 /**
415  * rht_for_each_entry - iterate over hash chain of given type
416  * @tpos:       the type * to use as a loop cursor.
417  * @pos:        the &struct rhash_head to use as a loop cursor.
418  * @tbl:        the &struct bucket_table
419  * @hash:       the hash value / bucket index
420  * @member:     name of the &struct rhash_head within the hashable struct.
421  */
422 #define rht_for_each_entry(tpos, pos, tbl, hash, member)                \
423         rht_for_each_entry_continue(tpos, pos, (tbl)->buckets[hash],    \
424                                     tbl, hash, member)
425
426 /**
427  * rht_for_each_entry_safe - safely iterate over hash chain of given type
428  * @tpos:       the type * to use as a loop cursor.
429  * @pos:        the &struct rhash_head to use as a loop cursor.
430  * @next:       the &struct rhash_head to use as next in loop cursor.
431  * @tbl:        the &struct bucket_table
432  * @hash:       the hash value / bucket index
433  * @member:     name of the &struct rhash_head within the hashable struct.
434  *
435  * This hash chain list-traversal primitive allows for the looped code to
436  * remove the loop cursor from the list.
437  */
438 #define rht_for_each_entry_safe(tpos, pos, next, tbl, hash, member)         \
439         for (pos = rht_dereference_bucket((tbl)->buckets[hash], tbl, hash), \
440              next = !rht_is_a_nulls(pos) ?                                  \
441                        rht_dereference_bucket(pos->next, tbl, hash) : NULL; \
442              (!rht_is_a_nulls(pos)) && rht_entry(tpos, pos, member);        \
443              pos = next,                                                    \
444              next = !rht_is_a_nulls(pos) ?                                  \
445                        rht_dereference_bucket(pos->next, tbl, hash) : NULL)
446
447 /**
448  * rht_for_each_rcu_continue - continue iterating over rcu hash chain
449  * @pos:        the &struct rhash_head to use as a loop cursor.
450  * @head:       the previous &struct rhash_head to continue from
451  * @tbl:        the &struct bucket_table
452  * @hash:       the hash value / bucket index
453  *
454  * This hash chain list-traversal primitive may safely run concurrently with
455  * the _rcu mutation primitives such as rhashtable_insert() as long as the
456  * traversal is guarded by rcu_read_lock().
457  */
458 #define rht_for_each_rcu_continue(pos, head, tbl, hash)                 \
459         for (({barrier(); }),                                           \
460              pos = rht_dereference_bucket_rcu(head, tbl, hash);         \
461              !rht_is_a_nulls(pos);                                      \
462              pos = rcu_dereference_raw(pos->next))
463
464 /**
465  * rht_for_each_rcu - iterate over rcu hash chain
466  * @pos:        the &struct rhash_head to use as a loop cursor.
467  * @tbl:        the &struct bucket_table
468  * @hash:       the hash value / bucket index
469  *
470  * This hash chain list-traversal primitive may safely run concurrently with
471  * the _rcu mutation primitives such as rhashtable_insert() as long as the
472  * traversal is guarded by rcu_read_lock().
473  */
474 #define rht_for_each_rcu(pos, tbl, hash)                                \
475         rht_for_each_rcu_continue(pos, (tbl)->buckets[hash], tbl, hash)
476
477 /**
478  * rht_for_each_entry_rcu_continue - continue iterating over rcu hash chain
479  * @tpos:       the type * to use as a loop cursor.
480  * @pos:        the &struct rhash_head to use as a loop cursor.
481  * @head:       the previous &struct rhash_head to continue from
482  * @tbl:        the &struct bucket_table
483  * @hash:       the hash value / bucket index
484  * @member:     name of the &struct rhash_head within the hashable struct.
485  *
486  * This hash chain list-traversal primitive may safely run concurrently with
487  * the _rcu mutation primitives such as rhashtable_insert() as long as the
488  * traversal is guarded by rcu_read_lock().
489  */
490 #define rht_for_each_entry_rcu_continue(tpos, pos, head, tbl, hash, member) \
491         for (({barrier(); }),                                               \
492              pos = rht_dereference_bucket_rcu(head, tbl, hash);             \
493              (!rht_is_a_nulls(pos)) && rht_entry(tpos, pos, member);        \
494              pos = rht_dereference_bucket_rcu(pos->next, tbl, hash))
495
496 /**
497  * rht_for_each_entry_rcu - iterate over rcu hash chain of given type
498  * @tpos:       the type * to use as a loop cursor.
499  * @pos:        the &struct rhash_head to use as a loop cursor.
500  * @tbl:        the &struct bucket_table
501  * @hash:       the hash value / bucket index
502  * @member:     name of the &struct rhash_head within the hashable struct.
503  *
504  * This hash chain list-traversal primitive may safely run concurrently with
505  * the _rcu mutation primitives such as rhashtable_insert() as long as the
506  * traversal is guarded by rcu_read_lock().
507  */
508 #define rht_for_each_entry_rcu(tpos, pos, tbl, hash, member)            \
509         rht_for_each_entry_rcu_continue(tpos, pos, (tbl)->buckets[hash],\
510                                         tbl, hash, member)
511
512 static inline int rhashtable_compare(struct rhashtable_compare_arg *arg,
513                                      const void *obj)
514 {
515         struct rhashtable *ht = arg->ht;
516         const char *ptr = obj;
517
518         return memcmp(ptr + ht->p.key_offset, arg->key, ht->p.key_len);
519 }
520
521 /**
522  * rhashtable_lookup_fast - search hash table, inlined version
523  * @ht:         hash table
524  * @key:        the pointer to the key
525  * @params:     hash table parameters
526  *
527  * Computes the hash value for the key and traverses the bucket chain looking
528  * for a entry with an identical key. The first matching entry is returned.
529  *
530  * Returns the first entry on which the compare function returned true.
531  */
532 static inline void *rhashtable_lookup_fast(
533         struct rhashtable *ht, const void *key,
534         const struct rhashtable_params params)
535 {
536         struct rhashtable_compare_arg arg = {
537                 .ht = ht,
538                 .key = key,
539         };
540         const struct bucket_table *tbl;
541         struct rhash_head *he;
542         unsigned int hash;
543
544         rcu_read_lock();
545
546         tbl = rht_dereference_rcu(ht->tbl, ht);
547 restart:
548         hash = rht_key_hashfn(ht, tbl, key, params);
549         rht_for_each_rcu(he, tbl, hash) {
550                 if (params.obj_cmpfn ?
551                     params.obj_cmpfn(&arg, rht_obj(ht, he)) :
552                     rhashtable_compare(&arg, rht_obj(ht, he)))
553                         continue;
554                 rcu_read_unlock();
555                 return rht_obj(ht, he);
556         }
557
558         /* Ensure we see any new tables. */
559         smp_rmb();
560
561         tbl = rht_dereference_rcu(tbl->future_tbl, ht);
562         if (unlikely(tbl))
563                 goto restart;
564         rcu_read_unlock();
565
566         return NULL;
567 }
568
569 /* Internal function, please use rhashtable_insert_fast() instead */
570 static inline int __rhashtable_insert_fast(
571         struct rhashtable *ht, const void *key, struct rhash_head *obj,
572         const struct rhashtable_params params)
573 {
574         struct rhashtable_compare_arg arg = {
575                 .ht = ht,
576                 .key = key,
577         };
578         struct bucket_table *tbl, *new_tbl;
579         struct rhash_head *head;
580         spinlock_t *lock;
581         unsigned int elasticity;
582         unsigned int hash;
583         int err;
584
585 restart:
586         rcu_read_lock();
587
588         tbl = rht_dereference_rcu(ht->tbl, ht);
589
590         /* All insertions must grab the oldest table containing
591          * the hashed bucket that is yet to be rehashed.
592          */
593         for (;;) {
594                 hash = rht_head_hashfn(ht, tbl, obj, params);
595                 lock = rht_bucket_lock(tbl, hash);
596                 spin_lock_bh(lock);
597
598                 if (tbl->rehash <= hash)
599                         break;
600
601                 spin_unlock_bh(lock);
602                 tbl = rht_dereference_rcu(tbl->future_tbl, ht);
603         }
604
605         new_tbl = rht_dereference_rcu(tbl->future_tbl, ht);
606         if (unlikely(new_tbl)) {
607                 tbl = rhashtable_insert_slow(ht, key, obj, new_tbl);
608                 if (!IS_ERR_OR_NULL(tbl))
609                         goto slow_path;
610
611                 err = PTR_ERR(tbl);
612                 goto out;
613         }
614
615         err = -E2BIG;
616         if (unlikely(rht_grow_above_max(ht, tbl)))
617                 goto out;
618
619         if (unlikely(rht_grow_above_100(ht, tbl))) {
620 slow_path:
621                 spin_unlock_bh(lock);
622                 err = rhashtable_insert_rehash(ht, tbl);
623                 rcu_read_unlock();
624                 if (err)
625                         return err;
626
627                 goto restart;
628         }
629
630         err = -EEXIST;
631         elasticity = ht->elasticity;
632         rht_for_each(head, tbl, hash) {
633                 if (key &&
634                     unlikely(!(params.obj_cmpfn ?
635                                params.obj_cmpfn(&arg, rht_obj(ht, head)) :
636                                rhashtable_compare(&arg, rht_obj(ht, head)))))
637                         goto out;
638                 if (!--elasticity)
639                         goto slow_path;
640         }
641
642         err = 0;
643
644         head = rht_dereference_bucket(tbl->buckets[hash], tbl, hash);
645
646         RCU_INIT_POINTER(obj->next, head);
647
648         rcu_assign_pointer(tbl->buckets[hash], obj);
649
650         atomic_inc(&ht->nelems);
651         if (rht_grow_above_75(ht, tbl))
652                 schedule_work(&ht->run_work);
653
654 out:
655         spin_unlock_bh(lock);
656         rcu_read_unlock();
657
658         return err;
659 }
660
661 /**
662  * rhashtable_insert_fast - insert object into hash table
663  * @ht:         hash table
664  * @obj:        pointer to hash head inside object
665  * @params:     hash table parameters
666  *
667  * Will take a per bucket spinlock to protect against mutual mutations
668  * on the same bucket. Multiple insertions may occur in parallel unless
669  * they map to the same bucket lock.
670  *
671  * It is safe to call this function from atomic context.
672  *
673  * Will trigger an automatic deferred table resizing if the size grows
674  * beyond the watermark indicated by grow_decision() which can be passed
675  * to rhashtable_init().
676  */
677 static inline int rhashtable_insert_fast(
678         struct rhashtable *ht, struct rhash_head *obj,
679         const struct rhashtable_params params)
680 {
681         return __rhashtable_insert_fast(ht, NULL, obj, params);
682 }
683
684 /**
685  * rhashtable_lookup_insert_fast - lookup and insert object into hash table
686  * @ht:         hash table
687  * @obj:        pointer to hash head inside object
688  * @params:     hash table parameters
689  *
690  * Locks down the bucket chain in both the old and new table if a resize
691  * is in progress to ensure that writers can't remove from the old table
692  * and can't insert to the new table during the atomic operation of search
693  * and insertion. Searches for duplicates in both the old and new table if
694  * a resize is in progress.
695  *
696  * This lookup function may only be used for fixed key hash table (key_len
697  * parameter set). It will BUG() if used inappropriately.
698  *
699  * It is safe to call this function from atomic context.
700  *
701  * Will trigger an automatic deferred table resizing if the size grows
702  * beyond the watermark indicated by grow_decision() which can be passed
703  * to rhashtable_init().
704  */
705 static inline int rhashtable_lookup_insert_fast(
706         struct rhashtable *ht, struct rhash_head *obj,
707         const struct rhashtable_params params)
708 {
709         const char *key = rht_obj(ht, obj);
710
711         BUG_ON(ht->p.obj_hashfn);
712
713         return __rhashtable_insert_fast(ht, key + ht->p.key_offset, obj,
714                                         params);
715 }
716
717 /**
718  * rhashtable_lookup_insert_key - search and insert object to hash table
719  *                                with explicit key
720  * @ht:         hash table
721  * @key:        key
722  * @obj:        pointer to hash head inside object
723  * @params:     hash table parameters
724  *
725  * Locks down the bucket chain in both the old and new table if a resize
726  * is in progress to ensure that writers can't remove from the old table
727  * and can't insert to the new table during the atomic operation of search
728  * and insertion. Searches for duplicates in both the old and new table if
729  * a resize is in progress.
730  *
731  * Lookups may occur in parallel with hashtable mutations and resizing.
732  *
733  * Will trigger an automatic deferred table resizing if the size grows
734  * beyond the watermark indicated by grow_decision() which can be passed
735  * to rhashtable_init().
736  *
737  * Returns zero on success.
738  */
739 static inline int rhashtable_lookup_insert_key(
740         struct rhashtable *ht, const void *key, struct rhash_head *obj,
741         const struct rhashtable_params params)
742 {
743         BUG_ON(!ht->p.obj_hashfn || !key);
744
745         return __rhashtable_insert_fast(ht, key, obj, params);
746 }
747
748 /* Internal function, please use rhashtable_remove_fast() instead */
749 static inline int __rhashtable_remove_fast(
750         struct rhashtable *ht, struct bucket_table *tbl,
751         struct rhash_head *obj, const struct rhashtable_params params)
752 {
753         struct rhash_head __rcu **pprev;
754         struct rhash_head *he;
755         spinlock_t * lock;
756         unsigned int hash;
757         int err = -ENOENT;
758
759         hash = rht_head_hashfn(ht, tbl, obj, params);
760         lock = rht_bucket_lock(tbl, hash);
761
762         spin_lock_bh(lock);
763
764         pprev = &tbl->buckets[hash];
765         rht_for_each(he, tbl, hash) {
766                 if (he != obj) {
767                         pprev = &he->next;
768                         continue;
769                 }
770
771                 rcu_assign_pointer(*pprev, obj->next);
772                 err = 0;
773                 break;
774         }
775
776         spin_unlock_bh(lock);
777
778         return err;
779 }
780
781 /**
782  * rhashtable_remove_fast - remove object from hash table
783  * @ht:         hash table
784  * @obj:        pointer to hash head inside object
785  * @params:     hash table parameters
786  *
787  * Since the hash chain is single linked, the removal operation needs to
788  * walk the bucket chain upon removal. The removal operation is thus
789  * considerable slow if the hash table is not correctly sized.
790  *
791  * Will automatically shrink the table via rhashtable_expand() if the
792  * shrink_decision function specified at rhashtable_init() returns true.
793  *
794  * Returns zero on success, -ENOENT if the entry could not be found.
795  */
796 static inline int rhashtable_remove_fast(
797         struct rhashtable *ht, struct rhash_head *obj,
798         const struct rhashtable_params params)
799 {
800         struct bucket_table *tbl;
801         int err;
802
803         rcu_read_lock();
804
805         tbl = rht_dereference_rcu(ht->tbl, ht);
806
807         /* Because we have already taken (and released) the bucket
808          * lock in old_tbl, if we find that future_tbl is not yet
809          * visible then that guarantees the entry to still be in
810          * the old tbl if it exists.
811          */
812         while ((err = __rhashtable_remove_fast(ht, tbl, obj, params)) &&
813                (tbl = rht_dereference_rcu(tbl->future_tbl, ht)))
814                 ;
815
816         if (err)
817                 goto out;
818
819         atomic_dec(&ht->nelems);
820         if (unlikely(ht->p.automatic_shrinking &&
821                      rht_shrink_below_30(ht, tbl)))
822                 schedule_work(&ht->run_work);
823
824 out:
825         rcu_read_unlock();
826
827         return err;
828 }
829
830 /* Internal function, please use rhashtable_replace_fast() instead */
831 static inline int __rhashtable_replace_fast(
832         struct rhashtable *ht, struct bucket_table *tbl,
833         struct rhash_head *obj_old, struct rhash_head *obj_new,
834         const struct rhashtable_params params)
835 {
836         struct rhash_head __rcu **pprev;
837         struct rhash_head *he;
838         spinlock_t *lock;
839         unsigned int hash;
840         int err = -ENOENT;
841
842         /* Minimally, the old and new objects must have same hash
843          * (which should mean identifiers are the same).
844          */
845         hash = rht_head_hashfn(ht, tbl, obj_old, params);
846         if (hash != rht_head_hashfn(ht, tbl, obj_new, params))
847                 return -EINVAL;
848
849         lock = rht_bucket_lock(tbl, hash);
850
851         spin_lock_bh(lock);
852
853         pprev = &tbl->buckets[hash];
854         rht_for_each(he, tbl, hash) {
855                 if (he != obj_old) {
856                         pprev = &he->next;
857                         continue;
858                 }
859
860                 rcu_assign_pointer(obj_new->next, obj_old->next);
861                 rcu_assign_pointer(*pprev, obj_new);
862                 err = 0;
863                 break;
864         }
865
866         spin_unlock_bh(lock);
867
868         return err;
869 }
870
871 /**
872  * rhashtable_replace_fast - replace an object in hash table
873  * @ht:         hash table
874  * @obj_old:    pointer to hash head inside object being replaced
875  * @obj_new:    pointer to hash head inside object which is new
876  * @params:     hash table parameters
877  *
878  * Replacing an object doesn't affect the number of elements in the hash table
879  * or bucket, so we don't need to worry about shrinking or expanding the
880  * table here.
881  *
882  * Returns zero on success, -ENOENT if the entry could not be found,
883  * -EINVAL if hash is not the same for the old and new objects.
884  */
885 static inline int rhashtable_replace_fast(
886         struct rhashtable *ht, struct rhash_head *obj_old,
887         struct rhash_head *obj_new,
888         const struct rhashtable_params params)
889 {
890         struct bucket_table *tbl;
891         int err;
892
893         rcu_read_lock();
894
895         tbl = rht_dereference_rcu(ht->tbl, ht);
896
897         /* Because we have already taken (and released) the bucket
898          * lock in old_tbl, if we find that future_tbl is not yet
899          * visible then that guarantees the entry to still be in
900          * the old tbl if it exists.
901          */
902         while ((err = __rhashtable_replace_fast(ht, tbl, obj_old,
903                                                 obj_new, params)) &&
904                (tbl = rht_dereference_rcu(tbl->future_tbl, ht)))
905                 ;
906
907         rcu_read_unlock();
908
909         return err;
910 }
911
912 #endif /* _LINUX_RHASHTABLE_H */