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