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