xref: /linux/kernel/bpf/hashtab.c (revision a3a81d247651218e47153f2d2afd7aee236726fd)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  */
5 #include <linux/bpf.h>
6 #include <linux/btf.h>
7 #include <linux/jhash.h>
8 #include <linux/filter.h>
9 #include <linux/rculist_nulls.h>
10 #include <linux/rcupdate_wait.h>
11 #include <linux/random.h>
12 #include <linux/rhashtable.h>
13 #include <uapi/linux/btf.h>
14 #include <linux/rcupdate_trace.h>
15 #include <linux/btf_ids.h>
16 #include "percpu_freelist.h"
17 #include "bpf_lru_list.h"
18 #include "map_in_map.h"
19 #include <linux/bpf_mem_alloc.h>
20 #include <asm/rqspinlock.h>
21 
22 #define HTAB_CREATE_FLAG_MASK						\
23 	(BPF_F_NO_PREALLOC | BPF_F_NO_COMMON_LRU | BPF_F_NUMA_NODE |	\
24 	 BPF_F_ACCESS_MASK | BPF_F_ZERO_SEED)
25 
26 #define BATCH_OPS(_name)			\
27 	.map_lookup_batch =			\
28 	_name##_map_lookup_batch,		\
29 	.map_lookup_and_delete_batch =		\
30 	_name##_map_lookup_and_delete_batch,	\
31 	.map_update_batch =			\
32 	generic_map_update_batch,		\
33 	.map_delete_batch =			\
34 	generic_map_delete_batch
35 
36 /*
37  * The bucket lock has two protection scopes:
38  *
39  * 1) Serializing concurrent operations from BPF programs on different
40  *    CPUs
41  *
42  * 2) Serializing concurrent operations from BPF programs and sys_bpf()
43  *
44  * BPF programs can execute in any context including perf, kprobes and
45  * tracing. As there are almost no limits where perf, kprobes and tracing
46  * can be invoked from the lock operations need to be protected against
47  * deadlocks. Deadlocks can be caused by recursion and by an invocation in
48  * the lock held section when functions which acquire this lock are invoked
49  * from sys_bpf(). BPF recursion is prevented by incrementing the per CPU
50  * variable bpf_prog_active, which prevents BPF programs attached to perf
51  * events, kprobes and tracing to be invoked before the prior invocation
52  * from one of these contexts completed. sys_bpf() uses the same mechanism
53  * by pinning the task to the current CPU and incrementing the recursion
54  * protection across the map operation.
55  *
56  * This has subtle implications on PREEMPT_RT. PREEMPT_RT forbids certain
57  * operations like memory allocations (even with GFP_ATOMIC) from atomic
58  * contexts. This is required because even with GFP_ATOMIC the memory
59  * allocator calls into code paths which acquire locks with long held lock
60  * sections. To ensure the deterministic behaviour these locks are regular
61  * spinlocks, which are converted to 'sleepable' spinlocks on RT. The only
62  * true atomic contexts on an RT kernel are the low level hardware
63  * handling, scheduling, low level interrupt handling, NMIs etc. None of
64  * these contexts should ever do memory allocations.
65  *
66  * As regular device interrupt handlers and soft interrupts are forced into
67  * thread context, the existing code which does
68  *   spin_lock*(); alloc(GFP_ATOMIC); spin_unlock*();
69  * just works.
70  *
71  * In theory the BPF locks could be converted to regular spinlocks as well,
72  * but the bucket locks and percpu_freelist locks can be taken from
73  * arbitrary contexts (perf, kprobes, tracepoints) which are required to be
74  * atomic contexts even on RT. Before the introduction of bpf_mem_alloc,
75  * it is only safe to use raw spinlock for preallocated hash map on a RT kernel,
76  * because there is no memory allocation within the lock held sections. However
77  * after hash map was fully converted to use bpf_mem_alloc, there will be
78  * non-synchronous memory allocation for non-preallocated hash map, so it is
79  * safe to always use raw spinlock for bucket lock.
80  */
81 struct bucket {
82 	struct hlist_nulls_head head;
83 	rqspinlock_t raw_lock;
84 };
85 
86 struct bpf_htab {
87 	struct bpf_map map;
88 	struct bpf_mem_alloc ma;
89 	struct bpf_mem_alloc pcpu_ma;
90 	struct bucket *buckets;
91 	void *elems;
92 	union {
93 		struct pcpu_freelist freelist;
94 		struct bpf_lru lru;
95 	};
96 	struct htab_elem *__percpu *extra_elems;
97 	/* number of elements in non-preallocated hashtable are kept
98 	 * in either pcount or count
99 	 */
100 	struct percpu_counter pcount;
101 	atomic_t count;
102 	bool use_percpu_counter;
103 	u32 n_buckets;	/* number of hash buckets */
104 	u32 elem_size;	/* size of each element in bytes */
105 	u32 hashrnd;
106 };
107 
108 /* each htab element is struct htab_elem + key + value */
109 struct htab_elem {
110 	union {
111 		struct hlist_nulls_node hash_node;
112 		struct {
113 			void *padding;
114 			union {
115 				struct pcpu_freelist_node fnode;
116 				struct htab_elem *batch_flink;
117 			};
118 		};
119 	};
120 	union {
121 		/* pointer to per-cpu pointer */
122 		void *ptr_to_pptr;
123 		struct bpf_lru_node lru_node;
124 	};
125 	u32 hash;
126 	char key[] __aligned(8);
127 };
128 
129 struct htab_btf_record {
130 	struct btf_record *record;
131 	u32 key_size;
132 };
133 
134 static inline bool htab_is_prealloc(const struct bpf_htab *htab)
135 {
136 	return !(htab->map.map_flags & BPF_F_NO_PREALLOC);
137 }
138 
139 static void htab_init_buckets(struct bpf_htab *htab)
140 {
141 	unsigned int i;
142 
143 	for (i = 0; i < htab->n_buckets; i++) {
144 		INIT_HLIST_NULLS_HEAD(&htab->buckets[i].head, i);
145 		raw_res_spin_lock_init(&htab->buckets[i].raw_lock);
146 		cond_resched();
147 	}
148 }
149 
150 static inline int htab_lock_bucket(struct bucket *b, unsigned long *pflags)
151 {
152 	unsigned long flags;
153 	int ret;
154 
155 	ret = raw_res_spin_lock_irqsave(&b->raw_lock, flags);
156 	if (ret)
157 		return ret;
158 	*pflags = flags;
159 	return 0;
160 }
161 
162 static inline void htab_unlock_bucket(struct bucket *b, unsigned long flags)
163 {
164 	raw_res_spin_unlock_irqrestore(&b->raw_lock, flags);
165 }
166 
167 static bool htab_lru_map_delete_node(void *arg, struct bpf_lru_node *node);
168 
169 static bool htab_is_lru(const struct bpf_htab *htab)
170 {
171 	return htab->map.map_type == BPF_MAP_TYPE_LRU_HASH ||
172 		htab->map.map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH;
173 }
174 
175 static bool htab_is_percpu(const struct bpf_htab *htab)
176 {
177 	return htab->map.map_type == BPF_MAP_TYPE_PERCPU_HASH ||
178 		htab->map.map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH;
179 }
180 
181 static inline bool is_fd_htab(const struct bpf_htab *htab)
182 {
183 	return htab->map.map_type == BPF_MAP_TYPE_HASH_OF_MAPS;
184 }
185 
186 static inline void *htab_elem_value(struct htab_elem *l, u32 key_size)
187 {
188 	return l->key + round_up(key_size, 8);
189 }
190 
191 static inline void htab_elem_set_ptr(struct htab_elem *l, u32 key_size,
192 				     void __percpu *pptr)
193 {
194 	*(void __percpu **)htab_elem_value(l, key_size) = pptr;
195 }
196 
197 static inline void __percpu *htab_elem_get_ptr(struct htab_elem *l, u32 key_size)
198 {
199 	return *(void __percpu **)htab_elem_value(l, key_size);
200 }
201 
202 static void *fd_htab_map_get_ptr(const struct bpf_map *map, struct htab_elem *l)
203 {
204 	return *(void **)htab_elem_value(l, map->key_size);
205 }
206 
207 static struct htab_elem *get_htab_elem(struct bpf_htab *htab, int i)
208 {
209 	return (struct htab_elem *) (htab->elems + i * (u64)htab->elem_size);
210 }
211 
212 /* Both percpu and fd htab support in-place update, so no need for
213  * extra elem. LRU itself can remove the least used element, so
214  * there is no need for an extra elem during map_update.
215  */
216 static bool htab_has_extra_elems(struct bpf_htab *htab)
217 {
218 	return !htab_is_percpu(htab) && !htab_is_lru(htab) && !is_fd_htab(htab);
219 }
220 
221 static void htab_free_prealloced_internal_structs(struct bpf_htab *htab)
222 {
223 	u32 num_entries = htab->map.max_entries;
224 	int i;
225 
226 	if (htab_has_extra_elems(htab))
227 		num_entries += num_possible_cpus();
228 
229 	for (i = 0; i < num_entries; i++) {
230 		struct htab_elem *elem;
231 
232 		elem = get_htab_elem(htab, i);
233 		bpf_map_free_internal_structs(&htab->map,
234 					      htab_elem_value(elem, htab->map.key_size));
235 		cond_resched();
236 	}
237 }
238 
239 static void htab_free_prealloced_fields(struct bpf_htab *htab)
240 {
241 	u32 num_entries = htab->map.max_entries;
242 	int i;
243 
244 	if (IS_ERR_OR_NULL(htab->map.record))
245 		return;
246 	/*
247 	 * Preallocated maps do not have a bpf_mem_alloc destructor, so fully
248 	 * destroy every element, including the extra elements.
249 	 */
250 	if (htab_has_extra_elems(htab))
251 		num_entries += num_possible_cpus();
252 	for (i = 0; i < num_entries; i++) {
253 		struct htab_elem *elem;
254 
255 		elem = get_htab_elem(htab, i);
256 		if (htab_is_percpu(htab)) {
257 			void __percpu *pptr = htab_elem_get_ptr(elem, htab->map.key_size);
258 			int cpu;
259 
260 			for_each_possible_cpu(cpu) {
261 				bpf_obj_free_fields(htab->map.record, per_cpu_ptr(pptr, cpu));
262 				cond_resched();
263 			}
264 		} else {
265 			bpf_obj_free_fields(htab->map.record,
266 					    htab_elem_value(elem, htab->map.key_size));
267 			cond_resched();
268 		}
269 		cond_resched();
270 	}
271 }
272 
273 static void htab_free_elems(struct bpf_htab *htab)
274 {
275 	int i;
276 
277 	if (!htab_is_percpu(htab))
278 		goto free_elems;
279 
280 	for (i = 0; i < htab->map.max_entries; i++) {
281 		void __percpu *pptr;
282 
283 		pptr = htab_elem_get_ptr(get_htab_elem(htab, i),
284 					 htab->map.key_size);
285 		free_percpu(pptr);
286 		cond_resched();
287 	}
288 free_elems:
289 	bpf_map_area_free(htab->elems);
290 }
291 
292 /* The LRU list has a lock (lru_lock). Each htab bucket has a lock
293  * (bucket_lock). If both locks need to be acquired together, the lock
294  * order is always lru_lock -> bucket_lock and this only happens in
295  * bpf_lru_list.c logic. For example, certain code path of
296  * bpf_lru_pop_free(), which is called by function prealloc_lru_pop(),
297  * will acquire lru_lock first followed by acquiring bucket_lock.
298  *
299  * In hashtab.c, to avoid deadlock, lock acquisition of
300  * bucket_lock followed by lru_lock is not allowed. In such cases,
301  * bucket_lock needs to be released first before acquiring lru_lock.
302  */
303 static struct htab_elem *prealloc_lru_pop(struct bpf_htab *htab, void *key,
304 					  u32 hash)
305 {
306 	struct bpf_lru_node *node = bpf_lru_pop_free(&htab->lru, hash);
307 	struct htab_elem *l;
308 
309 	if (node) {
310 		bpf_map_inc_elem_count(&htab->map);
311 		l = container_of(node, struct htab_elem, lru_node);
312 		memcpy(l->key, key, htab->map.key_size);
313 		return l;
314 	}
315 
316 	return NULL;
317 }
318 
319 static int prealloc_init(struct bpf_htab *htab)
320 {
321 	u32 num_entries = htab->map.max_entries;
322 	int err = -ENOMEM, i;
323 
324 	if (htab_has_extra_elems(htab))
325 		num_entries += num_possible_cpus();
326 
327 	htab->elems = bpf_map_area_alloc((u64)htab->elem_size * num_entries,
328 					 htab->map.numa_node);
329 	if (!htab->elems)
330 		return -ENOMEM;
331 
332 	if (!htab_is_percpu(htab))
333 		goto skip_percpu_elems;
334 
335 	for (i = 0; i < num_entries; i++) {
336 		u32 size = round_up(htab->map.value_size, 8);
337 		void __percpu *pptr;
338 
339 		pptr = bpf_map_alloc_percpu(&htab->map, size, 8,
340 					    GFP_USER | __GFP_NOWARN);
341 		if (!pptr)
342 			goto free_elems;
343 		htab_elem_set_ptr(get_htab_elem(htab, i), htab->map.key_size,
344 				  pptr);
345 		cond_resched();
346 	}
347 
348 skip_percpu_elems:
349 	if (htab_is_lru(htab))
350 		err = bpf_lru_init(&htab->lru,
351 				   htab->map.map_flags & BPF_F_NO_COMMON_LRU,
352 				   offsetof(struct htab_elem, hash) -
353 				   offsetof(struct htab_elem, lru_node),
354 				   htab_lru_map_delete_node,
355 				   htab);
356 	else
357 		err = pcpu_freelist_init(&htab->freelist);
358 
359 	if (err)
360 		goto free_elems;
361 
362 	if (htab_is_lru(htab))
363 		bpf_lru_populate(&htab->lru, htab->elems,
364 				 offsetof(struct htab_elem, lru_node),
365 				 htab->elem_size, num_entries);
366 	else
367 		pcpu_freelist_populate(&htab->freelist,
368 				       htab->elems + offsetof(struct htab_elem, fnode),
369 				       htab->elem_size, num_entries);
370 
371 	return 0;
372 
373 free_elems:
374 	htab_free_elems(htab);
375 	return err;
376 }
377 
378 static void prealloc_destroy(struct bpf_htab *htab)
379 {
380 	htab_free_elems(htab);
381 
382 	if (htab_is_lru(htab))
383 		bpf_lru_destroy(&htab->lru);
384 	else
385 		pcpu_freelist_destroy(&htab->freelist);
386 }
387 
388 static int alloc_extra_elems(struct bpf_htab *htab)
389 {
390 	struct htab_elem *__percpu *pptr, *l_new;
391 	struct pcpu_freelist_node *l;
392 	int cpu;
393 
394 	pptr = bpf_map_alloc_percpu(&htab->map, sizeof(struct htab_elem *), 8,
395 				    GFP_USER | __GFP_NOWARN);
396 	if (!pptr)
397 		return -ENOMEM;
398 
399 	for_each_possible_cpu(cpu) {
400 		l = pcpu_freelist_pop(&htab->freelist);
401 		/* pop will succeed, since prealloc_init()
402 		 * preallocated extra num_possible_cpus elements
403 		 */
404 		l_new = container_of(l, struct htab_elem, fnode);
405 		*per_cpu_ptr(pptr, cpu) = l_new;
406 	}
407 	htab->extra_elems = pptr;
408 	return 0;
409 }
410 
411 /* Called from syscall */
412 static int htab_map_alloc_check(union bpf_attr *attr)
413 {
414 	bool percpu = (attr->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
415 		       attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);
416 	bool lru = (attr->map_type == BPF_MAP_TYPE_LRU_HASH ||
417 		    attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);
418 	/* percpu_lru means each cpu has its own LRU list.
419 	 * it is different from BPF_MAP_TYPE_PERCPU_HASH where
420 	 * the map's value itself is percpu.  percpu_lru has
421 	 * nothing to do with the map's value.
422 	 */
423 	bool percpu_lru = (attr->map_flags & BPF_F_NO_COMMON_LRU);
424 	bool prealloc = !(attr->map_flags & BPF_F_NO_PREALLOC);
425 	bool zero_seed = (attr->map_flags & BPF_F_ZERO_SEED);
426 	int numa_node = bpf_map_attr_numa_node(attr);
427 
428 	BUILD_BUG_ON(offsetof(struct htab_elem, fnode.next) !=
429 		     offsetof(struct htab_elem, hash_node.pprev));
430 
431 	if (zero_seed && !capable(CAP_SYS_ADMIN))
432 		/* Guard against local DoS, and discourage production use. */
433 		return -EPERM;
434 
435 	if (attr->map_flags & ~HTAB_CREATE_FLAG_MASK ||
436 	    !bpf_map_flags_access_ok(attr->map_flags))
437 		return -EINVAL;
438 
439 	if (!lru && percpu_lru)
440 		return -EINVAL;
441 
442 	if (lru && !prealloc)
443 		return -ENOTSUPP;
444 
445 	if (numa_node != NUMA_NO_NODE && (percpu || percpu_lru))
446 		return -EINVAL;
447 
448 	/* check sanity of attributes.
449 	 * value_size == 0 may be allowed in the future to use map as a set
450 	 */
451 	if (attr->max_entries == 0 || attr->key_size == 0 ||
452 	    attr->value_size == 0)
453 		return -EINVAL;
454 
455 	if ((u64)attr->key_size + attr->value_size >= KMALLOC_MAX_SIZE -
456 	   sizeof(struct htab_elem))
457 		/* if key_size + value_size is bigger, the user space won't be
458 		 * able to access the elements via bpf syscall. This check
459 		 * also makes sure that the elem_size doesn't overflow and it's
460 		 * kmalloc-able later in htab_map_update_elem()
461 		 */
462 		return -E2BIG;
463 	/* percpu map value size is bound by PCPU_MIN_UNIT_SIZE */
464 	if (percpu && round_up(attr->value_size, 8) > PCPU_MIN_UNIT_SIZE)
465 		return -E2BIG;
466 
467 	return 0;
468 }
469 
470 static void htab_mem_dtor(void *obj, void *ctx)
471 {
472 	struct htab_btf_record *hrec = ctx;
473 	struct htab_elem *elem = obj;
474 	void *map_value;
475 
476 	if (IS_ERR_OR_NULL(hrec->record))
477 		return;
478 
479 	map_value = htab_elem_value(elem, hrec->key_size);
480 	bpf_obj_free_fields(hrec->record, map_value);
481 }
482 
483 static void htab_pcpu_mem_dtor(void *obj, void *ctx)
484 {
485 	void __percpu *pptr = *(void __percpu **)obj;
486 	struct htab_btf_record *hrec = ctx;
487 	int cpu;
488 
489 	if (IS_ERR_OR_NULL(hrec->record))
490 		return;
491 
492 	for_each_possible_cpu(cpu)
493 		bpf_obj_free_fields(hrec->record, per_cpu_ptr(pptr, cpu));
494 }
495 
496 static void htab_dtor_ctx_free(void *ctx)
497 {
498 	struct htab_btf_record *hrec = ctx;
499 
500 	btf_record_free(hrec->record);
501 	kfree(ctx);
502 }
503 
504 static int bpf_ma_set_dtor(struct bpf_map *map, struct bpf_mem_alloc *ma,
505 			   void (*dtor)(void *, void *))
506 {
507 	struct htab_btf_record *hrec;
508 	int err;
509 
510 	/* No need for dtors. */
511 	if (IS_ERR_OR_NULL(map->record))
512 		return 0;
513 
514 	hrec = kzalloc(sizeof(*hrec), GFP_KERNEL);
515 	if (!hrec)
516 		return -ENOMEM;
517 	hrec->key_size = map->key_size;
518 	hrec->record = btf_record_dup(map->record);
519 	if (IS_ERR(hrec->record)) {
520 		err = PTR_ERR(hrec->record);
521 		kfree(hrec);
522 		return err;
523 	}
524 	bpf_mem_alloc_set_dtor(ma, dtor, htab_dtor_ctx_free, hrec);
525 	return 0;
526 }
527 
528 static int htab_map_check_btf(struct bpf_map *map, const struct btf *btf,
529 			      const struct btf_type *key_type, const struct btf_type *value_type)
530 {
531 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
532 
533 	if (htab_is_prealloc(htab))
534 		return 0;
535 	/*
536 	 * We must set the dtor using this callback, as map's BTF record is not
537 	 * populated in htab_map_alloc(), so it will always appear as NULL.
538 	 */
539 	if (htab_is_percpu(htab))
540 		return bpf_ma_set_dtor(map, &htab->pcpu_ma, htab_pcpu_mem_dtor);
541 	else
542 		return bpf_ma_set_dtor(map, &htab->ma, htab_mem_dtor);
543 }
544 
545 static struct bpf_map *htab_map_alloc(union bpf_attr *attr)
546 {
547 	bool percpu = (attr->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
548 		       attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);
549 	/* percpu_lru means each cpu has its own LRU list.
550 	 * it is different from BPF_MAP_TYPE_PERCPU_HASH where
551 	 * the map's value itself is percpu.  percpu_lru has
552 	 * nothing to do with the map's value.
553 	 */
554 	bool percpu_lru = (attr->map_flags & BPF_F_NO_COMMON_LRU);
555 	bool prealloc = !(attr->map_flags & BPF_F_NO_PREALLOC);
556 	struct bpf_htab *htab;
557 	int err;
558 
559 	htab = bpf_map_area_alloc(sizeof(*htab), NUMA_NO_NODE);
560 	if (!htab)
561 		return ERR_PTR(-ENOMEM);
562 
563 	bpf_map_init_from_attr(&htab->map, attr);
564 
565 	if (percpu_lru) {
566 		/* ensure each CPU's lru list has >=1 elements.
567 		 * since we are at it, make each lru list has the same
568 		 * number of elements.
569 		 */
570 		htab->map.max_entries = roundup(attr->max_entries,
571 						num_possible_cpus());
572 		if (htab->map.max_entries < attr->max_entries)
573 			htab->map.max_entries = rounddown(attr->max_entries,
574 							  num_possible_cpus());
575 	}
576 
577 	/* hash table size must be power of 2; roundup_pow_of_two() can overflow
578 	 * into UB on 32-bit arches, so check that first
579 	 */
580 	err = -E2BIG;
581 	if (htab->map.max_entries > 1UL << 31)
582 		goto free_htab;
583 
584 	htab->n_buckets = roundup_pow_of_two(htab->map.max_entries);
585 
586 	htab->elem_size = sizeof(struct htab_elem) +
587 			  round_up(htab->map.key_size, 8);
588 	if (percpu)
589 		htab->elem_size += sizeof(void *);
590 	else
591 		htab->elem_size += round_up(htab->map.value_size, 8);
592 
593 	/* check for u32 overflow */
594 	if (htab->n_buckets > U32_MAX / sizeof(struct bucket))
595 		goto free_htab;
596 
597 	err = bpf_map_init_elem_count(&htab->map);
598 	if (err)
599 		goto free_htab;
600 
601 	err = -ENOMEM;
602 	htab->buckets = bpf_map_area_alloc(htab->n_buckets *
603 					   sizeof(struct bucket),
604 					   htab->map.numa_node);
605 	if (!htab->buckets)
606 		goto free_elem_count;
607 
608 	if (htab->map.map_flags & BPF_F_ZERO_SEED)
609 		htab->hashrnd = 0;
610 	else
611 		htab->hashrnd = get_random_u32();
612 
613 	htab_init_buckets(htab);
614 
615 /* compute_batch_value() computes batch value as num_online_cpus() * 2
616  * and __percpu_counter_compare() needs
617  * htab->max_entries - cur_number_of_elems to be more than batch * num_online_cpus()
618  * for percpu_counter to be faster than atomic_t. In practice the average bpf
619  * hash map size is 10k, which means that a system with 64 cpus will fill
620  * hashmap to 20% of 10k before percpu_counter becomes ineffective. Therefore
621  * define our own batch count as 32 then 10k hash map can be filled up to 80%:
622  * 10k - 8k > 32 _batch_ * 64 _cpus_
623  * and __percpu_counter_compare() will still be fast. At that point hash map
624  * collisions will dominate its performance anyway. Assume that hash map filled
625  * to 50+% isn't going to be O(1) and use the following formula to choose
626  * between percpu_counter and atomic_t.
627  */
628 #define PERCPU_COUNTER_BATCH 32
629 	if (attr->max_entries / 2 > num_online_cpus() * PERCPU_COUNTER_BATCH)
630 		htab->use_percpu_counter = true;
631 
632 	if (htab->use_percpu_counter) {
633 		err = percpu_counter_init(&htab->pcount, 0, GFP_KERNEL);
634 		if (err)
635 			goto free_map_locked;
636 	}
637 
638 	if (prealloc) {
639 		err = prealloc_init(htab);
640 		if (err)
641 			goto free_map_locked;
642 
643 		if (htab_has_extra_elems(htab)) {
644 			err = alloc_extra_elems(htab);
645 			if (err)
646 				goto free_prealloc;
647 		}
648 	} else {
649 		err = bpf_mem_alloc_init(&htab->ma, htab->elem_size, false);
650 		if (err)
651 			goto free_map_locked;
652 		if (percpu) {
653 			err = bpf_mem_alloc_init(&htab->pcpu_ma,
654 						 round_up(htab->map.value_size, 8), true);
655 			if (err)
656 				goto free_map_locked;
657 		}
658 	}
659 
660 	return &htab->map;
661 
662 free_prealloc:
663 	prealloc_destroy(htab);
664 free_map_locked:
665 	if (htab->use_percpu_counter)
666 		percpu_counter_destroy(&htab->pcount);
667 	bpf_map_area_free(htab->buckets);
668 	bpf_mem_alloc_destroy(&htab->pcpu_ma);
669 	bpf_mem_alloc_destroy(&htab->ma);
670 free_elem_count:
671 	bpf_map_free_elem_count(&htab->map);
672 free_htab:
673 	bpf_map_area_free(htab);
674 	return ERR_PTR(err);
675 }
676 
677 static inline u32 htab_map_hash(const void *key, u32 key_len, u32 hashrnd)
678 {
679 	if (likely(key_len % 4 == 0))
680 		return jhash2(key, key_len / 4, hashrnd);
681 	return jhash(key, key_len, hashrnd);
682 }
683 
684 static inline struct bucket *__select_bucket(struct bpf_htab *htab, u32 hash)
685 {
686 	return &htab->buckets[hash & (htab->n_buckets - 1)];
687 }
688 
689 static inline struct hlist_nulls_head *select_bucket(struct bpf_htab *htab, u32 hash)
690 {
691 	return &__select_bucket(htab, hash)->head;
692 }
693 
694 /* this lookup function can only be called with bucket lock taken */
695 static struct htab_elem *lookup_elem_raw(struct hlist_nulls_head *head, u32 hash,
696 					 void *key, u32 key_size)
697 {
698 	struct hlist_nulls_node *n;
699 	struct htab_elem *l;
700 
701 	hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
702 		if (l->hash == hash && !memcmp(&l->key, key, key_size))
703 			return l;
704 
705 	return NULL;
706 }
707 
708 /* can be called without bucket lock. it will repeat the loop in
709  * the unlikely event when elements moved from one bucket into another
710  * while link list is being walked
711  */
712 static struct htab_elem *lookup_nulls_elem_raw(struct hlist_nulls_head *head,
713 					       u32 hash, void *key,
714 					       u32 key_size, u32 n_buckets)
715 {
716 	struct hlist_nulls_node *n;
717 	struct htab_elem *l;
718 
719 again:
720 	hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
721 		if (l->hash == hash && !memcmp(&l->key, key, key_size))
722 			return l;
723 
724 	if (unlikely(get_nulls_value(n) != (hash & (n_buckets - 1))))
725 		goto again;
726 
727 	return NULL;
728 }
729 
730 /* Called from syscall or from eBPF program directly, so
731  * arguments have to match bpf_map_lookup_elem() exactly.
732  * The return value is adjusted by BPF instructions
733  * in htab_map_gen_lookup().
734  */
735 static void *__htab_map_lookup_elem(struct bpf_map *map, void *key)
736 {
737 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
738 	struct hlist_nulls_head *head;
739 	struct htab_elem *l;
740 	u32 hash, key_size;
741 
742 	WARN_ON_ONCE(!bpf_rcu_lock_held());
743 
744 	key_size = map->key_size;
745 
746 	hash = htab_map_hash(key, key_size, htab->hashrnd);
747 
748 	head = select_bucket(htab, hash);
749 
750 	l = lookup_nulls_elem_raw(head, hash, key, key_size, htab->n_buckets);
751 
752 	return l;
753 }
754 
755 static void *htab_map_lookup_elem(struct bpf_map *map, void *key)
756 {
757 	struct htab_elem *l = __htab_map_lookup_elem(map, key);
758 
759 	if (l)
760 		return htab_elem_value(l, map->key_size);
761 
762 	return NULL;
763 }
764 
765 /* inline bpf_map_lookup_elem() call.
766  * Instead of:
767  * bpf_prog
768  *   bpf_map_lookup_elem
769  *     map->ops->map_lookup_elem
770  *       htab_map_lookup_elem
771  *         __htab_map_lookup_elem
772  * do:
773  * bpf_prog
774  *   __htab_map_lookup_elem
775  */
776 static int htab_map_gen_lookup(struct bpf_map *map, struct bpf_insn *insn_buf)
777 {
778 	struct bpf_insn *insn = insn_buf;
779 	const int ret = BPF_REG_0;
780 
781 	BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
782 		     (void *(*)(struct bpf_map *map, void *key))NULL));
783 	*insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
784 	*insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 1);
785 	*insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
786 				offsetof(struct htab_elem, key) +
787 				round_up(map->key_size, 8));
788 	return insn - insn_buf;
789 }
790 
791 static __always_inline void *__htab_lru_map_lookup_elem(struct bpf_map *map,
792 							void *key, const bool mark)
793 {
794 	struct htab_elem *l = __htab_map_lookup_elem(map, key);
795 
796 	if (l) {
797 		if (mark)
798 			bpf_lru_node_set_ref(&l->lru_node);
799 		return htab_elem_value(l, map->key_size);
800 	}
801 
802 	return NULL;
803 }
804 
805 static void *htab_lru_map_lookup_elem(struct bpf_map *map, void *key)
806 {
807 	return __htab_lru_map_lookup_elem(map, key, true);
808 }
809 
810 static void *htab_lru_map_lookup_elem_sys(struct bpf_map *map, void *key)
811 {
812 	return __htab_lru_map_lookup_elem(map, key, false);
813 }
814 
815 static int htab_lru_map_gen_lookup(struct bpf_map *map,
816 				   struct bpf_insn *insn_buf)
817 {
818 	struct bpf_insn *insn = insn_buf;
819 	const int ret = BPF_REG_0;
820 	const int ref_reg = BPF_REG_1;
821 
822 	BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
823 		     (void *(*)(struct bpf_map *map, void *key))NULL));
824 	*insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
825 	*insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 4);
826 	*insn++ = BPF_LDX_MEM(BPF_B, ref_reg, ret,
827 			      offsetof(struct htab_elem, lru_node) +
828 			      offsetof(struct bpf_lru_node, ref));
829 	*insn++ = BPF_JMP_IMM(BPF_JNE, ref_reg, 0, 1);
830 	*insn++ = BPF_ST_MEM(BPF_B, ret,
831 			     offsetof(struct htab_elem, lru_node) +
832 			     offsetof(struct bpf_lru_node, ref),
833 			     1);
834 	*insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
835 				offsetof(struct htab_elem, key) +
836 				round_up(map->key_size, 8));
837 	return insn - insn_buf;
838 }
839 
840 static void check_and_cancel_fields(struct bpf_htab *htab,
841 				    struct htab_elem *elem)
842 {
843 	if (IS_ERR_OR_NULL(htab->map.record))
844 		return;
845 
846 	if (htab_is_percpu(htab)) {
847 		void __percpu *pptr = htab_elem_get_ptr(elem, htab->map.key_size);
848 		int cpu;
849 
850 		for_each_possible_cpu(cpu)
851 			bpf_obj_cancel_fields(&htab->map, per_cpu_ptr(pptr, cpu));
852 	} else {
853 		void *map_value = htab_elem_value(elem, htab->map.key_size);
854 
855 		bpf_obj_cancel_fields(&htab->map, map_value);
856 	}
857 }
858 
859 /* It is called from the bpf_lru_list when the LRU needs to delete
860  * older elements from the htab.
861  */
862 static bool htab_lru_map_delete_node(void *arg, struct bpf_lru_node *node)
863 {
864 	struct bpf_htab *htab = arg;
865 	struct htab_elem *l = NULL, *tgt_l;
866 	struct hlist_nulls_head *head;
867 	struct hlist_nulls_node *n;
868 	unsigned long flags;
869 	struct bucket *b;
870 	int ret;
871 
872 	tgt_l = container_of(node, struct htab_elem, lru_node);
873 	b = __select_bucket(htab, tgt_l->hash);
874 	head = &b->head;
875 
876 	ret = htab_lock_bucket(b, &flags);
877 	if (ret)
878 		return false;
879 
880 	hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
881 		if (l == tgt_l) {
882 			hlist_nulls_del_rcu(&l->hash_node);
883 			bpf_map_dec_elem_count(&htab->map);
884 			break;
885 		}
886 
887 	htab_unlock_bucket(b, flags);
888 
889 	if (l == tgt_l)
890 		check_and_cancel_fields(htab, l);
891 	return l == tgt_l;
892 }
893 
894 /* Called from syscall */
895 static int htab_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
896 {
897 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
898 	struct hlist_nulls_head *head;
899 	struct htab_elem *l, *next_l;
900 	u32 hash, key_size;
901 	int i = 0;
902 
903 	WARN_ON_ONCE(!rcu_read_lock_held());
904 
905 	key_size = map->key_size;
906 
907 	if (!key)
908 		goto find_first_elem;
909 
910 	hash = htab_map_hash(key, key_size, htab->hashrnd);
911 
912 	head = select_bucket(htab, hash);
913 
914 	/* lookup the key */
915 	l = lookup_nulls_elem_raw(head, hash, key, key_size, htab->n_buckets);
916 
917 	if (!l)
918 		goto find_first_elem;
919 
920 	/* key was found, get next key in the same bucket */
921 	next_l = hlist_nulls_entry_safe(rcu_dereference_raw(hlist_nulls_next_rcu(&l->hash_node)),
922 				  struct htab_elem, hash_node);
923 
924 	if (next_l) {
925 		/* if next elem in this hash list is non-zero, just return it */
926 		memcpy(next_key, next_l->key, key_size);
927 		return 0;
928 	}
929 
930 	/* no more elements in this hash list, go to the next bucket */
931 	i = hash & (htab->n_buckets - 1);
932 	i++;
933 
934 find_first_elem:
935 	/* iterate over buckets */
936 	for (; i < htab->n_buckets; i++) {
937 		head = select_bucket(htab, i);
938 
939 		/* pick first element in the bucket */
940 		next_l = hlist_nulls_entry_safe(rcu_dereference_raw(hlist_nulls_first_rcu(head)),
941 					  struct htab_elem, hash_node);
942 		if (next_l) {
943 			/* if it's not empty, just return it */
944 			memcpy(next_key, next_l->key, key_size);
945 			return 0;
946 		}
947 	}
948 
949 	/* iterated over all buckets and all elements */
950 	return -ENOENT;
951 }
952 
953 static void htab_elem_free(struct bpf_htab *htab, struct htab_elem *l)
954 {
955 	check_and_cancel_fields(htab, l);
956 
957 	if (htab->map.map_type == BPF_MAP_TYPE_PERCPU_HASH)
958 		bpf_mem_cache_free(&htab->pcpu_ma, l->ptr_to_pptr);
959 	bpf_mem_cache_free(&htab->ma, l);
960 }
961 
962 static void htab_put_fd_value(struct bpf_htab *htab, struct htab_elem *l)
963 {
964 	struct bpf_map *map = &htab->map;
965 	void *ptr;
966 
967 	if (map->ops->map_fd_put_ptr) {
968 		ptr = fd_htab_map_get_ptr(map, l);
969 		map->ops->map_fd_put_ptr(map, ptr, true);
970 	}
971 }
972 
973 static bool is_map_full(struct bpf_htab *htab)
974 {
975 	if (htab->use_percpu_counter)
976 		return __percpu_counter_compare(&htab->pcount, htab->map.max_entries,
977 						PERCPU_COUNTER_BATCH) >= 0;
978 	return atomic_read(&htab->count) >= htab->map.max_entries;
979 }
980 
981 static void inc_elem_count(struct bpf_htab *htab)
982 {
983 	bpf_map_inc_elem_count(&htab->map);
984 
985 	if (htab->use_percpu_counter)
986 		percpu_counter_add_batch(&htab->pcount, 1, PERCPU_COUNTER_BATCH);
987 	else
988 		atomic_inc(&htab->count);
989 }
990 
991 static void dec_elem_count(struct bpf_htab *htab)
992 {
993 	bpf_map_dec_elem_count(&htab->map);
994 
995 	if (htab->use_percpu_counter)
996 		percpu_counter_add_batch(&htab->pcount, -1, PERCPU_COUNTER_BATCH);
997 	else
998 		atomic_dec(&htab->count);
999 }
1000 
1001 
1002 static void free_htab_elem(struct bpf_htab *htab, struct htab_elem *l)
1003 {
1004 	htab_put_fd_value(htab, l);
1005 
1006 	if (htab_is_prealloc(htab)) {
1007 		bpf_map_dec_elem_count(&htab->map);
1008 		check_and_cancel_fields(htab, l);
1009 		pcpu_freelist_push(&htab->freelist, &l->fnode);
1010 	} else {
1011 		dec_elem_count(htab);
1012 		htab_elem_free(htab, l);
1013 	}
1014 }
1015 
1016 static void pcpu_copy_value(struct bpf_htab *htab, void __percpu *pptr,
1017 			    void *value, bool onallcpus, u64 map_flags)
1018 {
1019 	void *ptr;
1020 
1021 	if (!onallcpus) {
1022 		/* copy true value_size bytes */
1023 		ptr = this_cpu_ptr(pptr);
1024 		copy_map_value(&htab->map, ptr, value);
1025 		bpf_obj_cancel_fields(&htab->map, ptr);
1026 	} else {
1027 		u32 size = round_up(htab->map.value_size, 8);
1028 		void *val;
1029 		int cpu;
1030 
1031 		if (map_flags & BPF_F_CPU) {
1032 			cpu = map_flags >> 32;
1033 			ptr = per_cpu_ptr(pptr, cpu);
1034 			copy_map_value(&htab->map, ptr, value);
1035 			bpf_obj_cancel_fields(&htab->map, ptr);
1036 			return;
1037 		}
1038 
1039 		for_each_possible_cpu(cpu) {
1040 			ptr = per_cpu_ptr(pptr, cpu);
1041 			val = (map_flags & BPF_F_ALL_CPUS) ? value : value + size * cpu;
1042 			copy_map_value(&htab->map, ptr, val);
1043 			bpf_obj_cancel_fields(&htab->map, ptr);
1044 		}
1045 	}
1046 }
1047 
1048 static void pcpu_init_value(struct bpf_htab *htab, void __percpu *pptr,
1049 			    void *value, bool onallcpus, u64 map_flags)
1050 {
1051 	/* When not setting the initial value on all cpus, zero-fill element
1052 	 * values for other cpus. Otherwise, bpf program has no way to ensure
1053 	 * known initial values for cpus other than current one
1054 	 * (onallcpus=false always when coming from bpf prog).
1055 	 */
1056 	if (!onallcpus) {
1057 		int current_cpu = raw_smp_processor_id();
1058 		int cpu;
1059 
1060 		for_each_possible_cpu(cpu) {
1061 			if (cpu == current_cpu)
1062 				copy_map_value(&htab->map, per_cpu_ptr(pptr, cpu), value);
1063 			else /* Since elem is preallocated, we cannot touch special fields */
1064 				zero_map_value(&htab->map, per_cpu_ptr(pptr, cpu));
1065 		}
1066 	} else {
1067 		pcpu_copy_value(htab, pptr, value, onallcpus, map_flags);
1068 	}
1069 }
1070 
1071 static bool fd_htab_map_needs_adjust(const struct bpf_htab *htab)
1072 {
1073 	return is_fd_htab(htab) && BITS_PER_LONG == 64;
1074 }
1075 
1076 static struct htab_elem *alloc_htab_elem(struct bpf_htab *htab, void *key,
1077 					 void *value, u32 key_size, u32 hash,
1078 					 bool percpu, bool onallcpus,
1079 					 struct htab_elem *old_elem, u64 map_flags)
1080 {
1081 	u32 size = htab->map.value_size;
1082 	bool prealloc = htab_is_prealloc(htab);
1083 	struct htab_elem *l_new, **pl_new;
1084 	void __percpu *pptr;
1085 
1086 	if (prealloc) {
1087 		if (old_elem) {
1088 			/* if we're updating the existing element,
1089 			 * use per-cpu extra elems to avoid freelist_pop/push
1090 			 */
1091 			pl_new = this_cpu_ptr(htab->extra_elems);
1092 			l_new = *pl_new;
1093 			*pl_new = old_elem;
1094 		} else {
1095 			struct pcpu_freelist_node *l;
1096 
1097 			l = __pcpu_freelist_pop(&htab->freelist);
1098 			if (!l)
1099 				return ERR_PTR(-E2BIG);
1100 			l_new = container_of(l, struct htab_elem, fnode);
1101 			bpf_map_inc_elem_count(&htab->map);
1102 		}
1103 	} else {
1104 		if (is_map_full(htab))
1105 			if (!old_elem)
1106 				/* when map is full and update() is replacing
1107 				 * old element, it's ok to allocate, since
1108 				 * old element will be freed immediately.
1109 				 * Otherwise return an error
1110 				 */
1111 				return ERR_PTR(-E2BIG);
1112 		inc_elem_count(htab);
1113 		l_new = bpf_mem_cache_alloc(&htab->ma);
1114 		if (!l_new) {
1115 			l_new = ERR_PTR(-ENOMEM);
1116 			goto dec_count;
1117 		}
1118 	}
1119 
1120 	memcpy(l_new->key, key, key_size);
1121 	if (percpu) {
1122 		if (prealloc) {
1123 			pptr = htab_elem_get_ptr(l_new, key_size);
1124 		} else {
1125 			/* alloc_percpu zero-fills */
1126 			void *ptr = bpf_mem_cache_alloc(&htab->pcpu_ma);
1127 
1128 			if (!ptr) {
1129 				bpf_mem_cache_free(&htab->ma, l_new);
1130 				l_new = ERR_PTR(-ENOMEM);
1131 				goto dec_count;
1132 			}
1133 			l_new->ptr_to_pptr = ptr;
1134 			pptr = *(void __percpu **)ptr;
1135 		}
1136 
1137 		pcpu_init_value(htab, pptr, value, onallcpus, map_flags);
1138 
1139 		if (!prealloc)
1140 			htab_elem_set_ptr(l_new, key_size, pptr);
1141 	} else if (fd_htab_map_needs_adjust(htab)) {
1142 		size = round_up(size, 8);
1143 		memcpy(htab_elem_value(l_new, key_size), value, size);
1144 	} else if (map_flags & BPF_F_LOCK) {
1145 		copy_map_value_locked(&htab->map,
1146 				      htab_elem_value(l_new, key_size),
1147 				      value, false);
1148 	} else {
1149 		copy_map_value(&htab->map, htab_elem_value(l_new, key_size), value);
1150 	}
1151 
1152 	l_new->hash = hash;
1153 	return l_new;
1154 dec_count:
1155 	dec_elem_count(htab);
1156 	return l_new;
1157 }
1158 
1159 static int check_flags(struct bpf_htab *htab, struct htab_elem *l_old,
1160 		       u64 map_flags)
1161 {
1162 	if (l_old && (map_flags & ~BPF_F_LOCK) == BPF_NOEXIST)
1163 		/* elem already exists */
1164 		return -EEXIST;
1165 
1166 	if (!l_old && (map_flags & ~BPF_F_LOCK) == BPF_EXIST)
1167 		/* elem doesn't exist, cannot update it */
1168 		return -ENOENT;
1169 
1170 	return 0;
1171 }
1172 
1173 /* Called from syscall or from eBPF program */
1174 static long htab_map_update_elem(struct bpf_map *map, void *key, void *value,
1175 				 u64 map_flags)
1176 {
1177 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1178 	struct htab_elem *l_new, *l_old;
1179 	struct hlist_nulls_head *head;
1180 	unsigned long flags;
1181 	struct bucket *b;
1182 	u32 key_size, hash;
1183 	int ret;
1184 
1185 	if (unlikely((map_flags & ~BPF_F_LOCK) > BPF_EXIST))
1186 		/* unknown flags */
1187 		return -EINVAL;
1188 
1189 	WARN_ON_ONCE(!bpf_rcu_lock_held());
1190 
1191 	key_size = map->key_size;
1192 
1193 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1194 
1195 	b = __select_bucket(htab, hash);
1196 	head = &b->head;
1197 
1198 	if (unlikely(map_flags & BPF_F_LOCK)) {
1199 		if (unlikely(!btf_record_has_field(map->record, BPF_SPIN_LOCK)))
1200 			return -EINVAL;
1201 		/* find an element without taking the bucket lock */
1202 		l_old = lookup_nulls_elem_raw(head, hash, key, key_size,
1203 					      htab->n_buckets);
1204 		ret = check_flags(htab, l_old, map_flags);
1205 		if (ret)
1206 			return ret;
1207 		if (l_old) {
1208 			/* grab the element lock and update value in place */
1209 			copy_map_value_locked(map,
1210 					      htab_elem_value(l_old, key_size),
1211 					      value, false);
1212 			return 0;
1213 		}
1214 		/* fall through, grab the bucket lock and lookup again.
1215 		 * 99.9% chance that the element won't be found,
1216 		 * but second lookup under lock has to be done.
1217 		 */
1218 	}
1219 
1220 	ret = htab_lock_bucket(b, &flags);
1221 	if (ret)
1222 		return ret;
1223 
1224 	l_old = lookup_elem_raw(head, hash, key, key_size);
1225 
1226 	ret = check_flags(htab, l_old, map_flags);
1227 	if (ret)
1228 		goto err;
1229 
1230 	if (unlikely(l_old && (map_flags & BPF_F_LOCK))) {
1231 		/* first lookup without the bucket lock didn't find the element,
1232 		 * but second lookup with the bucket lock found it.
1233 		 * This case is highly unlikely, but has to be dealt with:
1234 		 * grab the element lock in addition to the bucket lock
1235 		 * and update element in place
1236 		 */
1237 		copy_map_value_locked(map,
1238 				      htab_elem_value(l_old, key_size),
1239 				      value, false);
1240 		ret = 0;
1241 		goto err;
1242 	}
1243 
1244 	l_new = alloc_htab_elem(htab, key, value, key_size, hash, false, false,
1245 				l_old, map_flags);
1246 	if (IS_ERR(l_new)) {
1247 		/* all pre-allocated elements are in use or memory exhausted */
1248 		ret = PTR_ERR(l_new);
1249 		goto err;
1250 	}
1251 
1252 	/* add new element to the head of the list, so that
1253 	 * concurrent search will find it before old elem
1254 	 */
1255 	hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1256 	if (l_old) {
1257 		hlist_nulls_del_rcu(&l_old->hash_node);
1258 
1259 		/* l_old has already been stashed in htab->extra_elems, cancel
1260 		 * its reusable special fields before it is available for reuse.
1261 		 */
1262 		if (htab_is_prealloc(htab))
1263 			check_and_cancel_fields(htab, l_old);
1264 	}
1265 	htab_unlock_bucket(b, flags);
1266 	if (l_old && !htab_is_prealloc(htab))
1267 		free_htab_elem(htab, l_old);
1268 	return 0;
1269 err:
1270 	htab_unlock_bucket(b, flags);
1271 	return ret;
1272 }
1273 
1274 static void htab_lru_push_free(struct bpf_htab *htab, struct htab_elem *elem)
1275 {
1276 	check_and_cancel_fields(htab, elem);
1277 	bpf_map_dec_elem_count(&htab->map);
1278 	bpf_lru_push_free(&htab->lru, &elem->lru_node);
1279 }
1280 
1281 static long htab_lru_map_update_elem(struct bpf_map *map, void *key, void *value,
1282 				     u64 map_flags)
1283 {
1284 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1285 	struct htab_elem *l_new, *l_old = NULL;
1286 	struct hlist_nulls_head *head;
1287 	unsigned long flags;
1288 	struct bucket *b;
1289 	u32 key_size, hash;
1290 	int ret;
1291 
1292 	if (unlikely(map_flags > BPF_EXIST))
1293 		/* unknown flags */
1294 		return -EINVAL;
1295 
1296 	WARN_ON_ONCE(!bpf_rcu_lock_held());
1297 
1298 	key_size = map->key_size;
1299 
1300 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1301 
1302 	b = __select_bucket(htab, hash);
1303 	head = &b->head;
1304 
1305 	/* For LRU, we need to alloc before taking bucket's
1306 	 * spinlock because getting free nodes from LRU may need
1307 	 * to remove older elements from htab and this removal
1308 	 * operation will need a bucket lock.
1309 	 */
1310 	l_new = prealloc_lru_pop(htab, key, hash);
1311 	if (!l_new)
1312 		return -ENOMEM;
1313 	copy_map_value(&htab->map, htab_elem_value(l_new, map->key_size), value);
1314 
1315 	ret = htab_lock_bucket(b, &flags);
1316 	if (ret)
1317 		goto err_lock_bucket;
1318 
1319 	l_old = lookup_elem_raw(head, hash, key, key_size);
1320 
1321 	ret = check_flags(htab, l_old, map_flags);
1322 	if (ret)
1323 		goto err;
1324 
1325 	/* add new element to the head of the list, so that
1326 	 * concurrent search will find it before old elem
1327 	 */
1328 	hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1329 	if (l_old) {
1330 		bpf_lru_node_set_ref(&l_new->lru_node);
1331 		hlist_nulls_del_rcu(&l_old->hash_node);
1332 	}
1333 	ret = 0;
1334 
1335 err:
1336 	htab_unlock_bucket(b, flags);
1337 
1338 err_lock_bucket:
1339 	if (ret)
1340 		htab_lru_push_free(htab, l_new);
1341 	else if (l_old)
1342 		htab_lru_push_free(htab, l_old);
1343 
1344 	return ret;
1345 }
1346 
1347 static int htab_map_check_update_flags(bool onallcpus, u64 map_flags)
1348 {
1349 	if (unlikely(!onallcpus && map_flags > BPF_EXIST))
1350 		return -EINVAL;
1351 	if (unlikely(onallcpus && ((map_flags & BPF_F_LOCK) || (u32)map_flags > BPF_F_ALL_CPUS)))
1352 		return -EINVAL;
1353 	return 0;
1354 }
1355 
1356 static long htab_map_update_elem_in_place(struct bpf_map *map, void *key,
1357 					  void *value, u64 map_flags,
1358 					  bool percpu, bool onallcpus)
1359 {
1360 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1361 	struct htab_elem *l_new, *l_old;
1362 	struct hlist_nulls_head *head;
1363 	void *old_map_ptr = NULL;
1364 	unsigned long flags;
1365 	struct bucket *b;
1366 	u32 key_size, hash;
1367 	int ret;
1368 
1369 	ret = htab_map_check_update_flags(onallcpus, map_flags);
1370 	if (unlikely(ret))
1371 		return ret;
1372 
1373 	WARN_ON_ONCE(!bpf_rcu_lock_held());
1374 
1375 	key_size = map->key_size;
1376 
1377 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1378 
1379 	b = __select_bucket(htab, hash);
1380 	head = &b->head;
1381 
1382 	ret = htab_lock_bucket(b, &flags);
1383 	if (ret)
1384 		return ret;
1385 
1386 	l_old = lookup_elem_raw(head, hash, key, key_size);
1387 
1388 	ret = check_flags(htab, l_old, map_flags);
1389 	if (ret)
1390 		goto err;
1391 
1392 	if (l_old) {
1393 		/* Update value in-place */
1394 		if (percpu) {
1395 			pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size),
1396 					value, onallcpus, map_flags);
1397 		} else {
1398 			void **inner_map_pptr = htab_elem_value(l_old, key_size);
1399 
1400 			old_map_ptr = *inner_map_pptr;
1401 			WRITE_ONCE(*inner_map_pptr, *(void **)value);
1402 		}
1403 	} else {
1404 		l_new = alloc_htab_elem(htab, key, value, key_size,
1405 					hash, percpu, onallcpus, NULL, map_flags);
1406 		if (IS_ERR(l_new)) {
1407 			ret = PTR_ERR(l_new);
1408 			goto err;
1409 		}
1410 		hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1411 	}
1412 err:
1413 	htab_unlock_bucket(b, flags);
1414 	if (old_map_ptr)
1415 		map->ops->map_fd_put_ptr(map, old_map_ptr, true);
1416 	return ret;
1417 }
1418 
1419 static long __htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key,
1420 					      void *value, u64 map_flags,
1421 					      bool onallcpus)
1422 {
1423 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1424 	struct htab_elem *l_new = NULL, *l_old;
1425 	struct hlist_nulls_head *head;
1426 	unsigned long flags;
1427 	struct bucket *b;
1428 	u32 key_size, hash;
1429 	int ret;
1430 
1431 	ret = htab_map_check_update_flags(onallcpus, map_flags);
1432 	if (unlikely(ret))
1433 		return ret;
1434 
1435 	WARN_ON_ONCE(!bpf_rcu_lock_held());
1436 
1437 	key_size = map->key_size;
1438 
1439 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1440 
1441 	b = __select_bucket(htab, hash);
1442 	head = &b->head;
1443 
1444 	/* For LRU, we need to alloc before taking bucket's
1445 	 * spinlock because LRU's elem alloc may need
1446 	 * to remove older elem from htab and this removal
1447 	 * operation will need a bucket lock.
1448 	 */
1449 	if (map_flags != BPF_EXIST) {
1450 		l_new = prealloc_lru_pop(htab, key, hash);
1451 		if (!l_new)
1452 			return -ENOMEM;
1453 	}
1454 
1455 	ret = htab_lock_bucket(b, &flags);
1456 	if (ret)
1457 		goto err_lock_bucket;
1458 
1459 	l_old = lookup_elem_raw(head, hash, key, key_size);
1460 
1461 	ret = check_flags(htab, l_old, map_flags);
1462 	if (ret)
1463 		goto err;
1464 
1465 	if (l_old) {
1466 		bpf_lru_node_set_ref(&l_old->lru_node);
1467 
1468 		/* per-cpu hash map can update value in-place */
1469 		pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size),
1470 				value, onallcpus, map_flags);
1471 	} else {
1472 		pcpu_init_value(htab, htab_elem_get_ptr(l_new, key_size),
1473 				value, onallcpus, map_flags);
1474 		hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1475 		l_new = NULL;
1476 	}
1477 	ret = 0;
1478 err:
1479 	htab_unlock_bucket(b, flags);
1480 err_lock_bucket:
1481 	if (l_new) {
1482 		bpf_map_dec_elem_count(&htab->map);
1483 		bpf_lru_push_free(&htab->lru, &l_new->lru_node);
1484 	}
1485 	return ret;
1486 }
1487 
1488 static long htab_percpu_map_update_elem(struct bpf_map *map, void *key,
1489 					void *value, u64 map_flags)
1490 {
1491 	return htab_map_update_elem_in_place(map, key, value, map_flags, true, false);
1492 }
1493 
1494 static long htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key,
1495 					    void *value, u64 map_flags)
1496 {
1497 	return __htab_lru_percpu_map_update_elem(map, key, value, map_flags,
1498 						 false);
1499 }
1500 
1501 /* Called from syscall or from eBPF program */
1502 static long htab_map_delete_elem(struct bpf_map *map, void *key)
1503 {
1504 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1505 	struct hlist_nulls_head *head;
1506 	struct bucket *b;
1507 	struct htab_elem *l;
1508 	unsigned long flags;
1509 	u32 hash, key_size;
1510 	int ret;
1511 
1512 	WARN_ON_ONCE(!bpf_rcu_lock_held());
1513 
1514 	key_size = map->key_size;
1515 
1516 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1517 	b = __select_bucket(htab, hash);
1518 	head = &b->head;
1519 
1520 	ret = htab_lock_bucket(b, &flags);
1521 	if (ret)
1522 		return ret;
1523 
1524 	l = lookup_elem_raw(head, hash, key, key_size);
1525 	if (l)
1526 		hlist_nulls_del_rcu(&l->hash_node);
1527 	else
1528 		ret = -ENOENT;
1529 
1530 	htab_unlock_bucket(b, flags);
1531 
1532 	if (l)
1533 		free_htab_elem(htab, l);
1534 	return ret;
1535 }
1536 
1537 static long htab_lru_map_delete_elem(struct bpf_map *map, void *key)
1538 {
1539 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1540 	struct hlist_nulls_head *head;
1541 	struct bucket *b;
1542 	struct htab_elem *l;
1543 	unsigned long flags;
1544 	u32 hash, key_size;
1545 	int ret;
1546 
1547 	WARN_ON_ONCE(!bpf_rcu_lock_held());
1548 
1549 	key_size = map->key_size;
1550 
1551 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1552 	b = __select_bucket(htab, hash);
1553 	head = &b->head;
1554 
1555 	ret = htab_lock_bucket(b, &flags);
1556 	if (ret)
1557 		return ret;
1558 
1559 	l = lookup_elem_raw(head, hash, key, key_size);
1560 
1561 	if (l)
1562 		hlist_nulls_del_rcu(&l->hash_node);
1563 	else
1564 		ret = -ENOENT;
1565 
1566 	htab_unlock_bucket(b, flags);
1567 	if (l)
1568 		htab_lru_push_free(htab, l);
1569 	return ret;
1570 }
1571 
1572 static void delete_all_elements(struct bpf_htab *htab)
1573 {
1574 	int i;
1575 
1576 	/* It's called from a worker thread and migration has been disabled,
1577 	 * therefore, it is OK to invoke bpf_mem_cache_free() directly.
1578 	 */
1579 	for (i = 0; i < htab->n_buckets; i++) {
1580 		struct hlist_nulls_head *head = select_bucket(htab, i);
1581 		struct hlist_nulls_node *n;
1582 		struct htab_elem *l;
1583 
1584 		hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
1585 			hlist_nulls_del_rcu(&l->hash_node);
1586 			htab_elem_free(htab, l);
1587 		}
1588 		cond_resched();
1589 	}
1590 }
1591 
1592 static void htab_free_malloced_internal_structs(struct bpf_htab *htab)
1593 {
1594 	int i;
1595 
1596 	rcu_read_lock();
1597 	for (i = 0; i < htab->n_buckets; i++) {
1598 		struct hlist_nulls_head *head = select_bucket(htab, i);
1599 		struct hlist_nulls_node *n;
1600 		struct htab_elem *l;
1601 
1602 		hlist_nulls_for_each_entry(l, n, head, hash_node) {
1603 			/* We only free internal structs on uref dropping to zero */
1604 			bpf_map_free_internal_structs(&htab->map,
1605 						      htab_elem_value(l, htab->map.key_size));
1606 		}
1607 		cond_resched_rcu();
1608 	}
1609 	rcu_read_unlock();
1610 }
1611 
1612 static void htab_map_free_internal_structs(struct bpf_map *map)
1613 {
1614 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1615 
1616 	/* We only free internal structs on uref dropping to zero */
1617 	if (!bpf_map_has_internal_structs(map))
1618 		return;
1619 
1620 	if (htab_is_prealloc(htab))
1621 		htab_free_prealloced_internal_structs(htab);
1622 	else
1623 		htab_free_malloced_internal_structs(htab);
1624 }
1625 
1626 /* Called when map->refcnt goes to zero, either from workqueue or from syscall */
1627 static void htab_map_free(struct bpf_map *map)
1628 {
1629 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1630 
1631 	/* bpf_free_used_maps() or close(map_fd) will trigger this map_free callback.
1632 	 * bpf_free_used_maps() is called after bpf prog is no longer executing.
1633 	 * There is no need to synchronize_rcu() here to protect map elements.
1634 	 */
1635 
1636 	/* htab no longer uses call_rcu() directly. bpf_mem_alloc does it
1637 	 * underneath and is responsible for waiting for callbacks to finish
1638 	 * during bpf_mem_alloc_destroy().
1639 	 */
1640 	if (!htab_is_prealloc(htab)) {
1641 		delete_all_elements(htab);
1642 	} else {
1643 		htab_free_prealloced_fields(htab);
1644 		prealloc_destroy(htab);
1645 	}
1646 
1647 	bpf_map_free_elem_count(map);
1648 	free_percpu(htab->extra_elems);
1649 	bpf_map_area_free(htab->buckets);
1650 	bpf_mem_alloc_destroy(&htab->pcpu_ma);
1651 	bpf_mem_alloc_destroy(&htab->ma);
1652 	if (htab->use_percpu_counter)
1653 		percpu_counter_destroy(&htab->pcount);
1654 	bpf_map_area_free(htab);
1655 }
1656 
1657 static void htab_map_seq_show_elem(struct bpf_map *map, void *key,
1658 				   struct seq_file *m)
1659 {
1660 	void *value;
1661 
1662 	rcu_read_lock();
1663 
1664 	value = htab_map_lookup_elem(map, key);
1665 	if (!value) {
1666 		rcu_read_unlock();
1667 		return;
1668 	}
1669 
1670 	btf_type_seq_show(map->btf, map->btf_key_type_id, key, m);
1671 	seq_puts(m, ": ");
1672 	btf_type_seq_show(map->btf, map->btf_value_type_id, value, m);
1673 	seq_putc(m, '\n');
1674 
1675 	rcu_read_unlock();
1676 }
1677 
1678 static int __htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
1679 					     void *value, bool is_lru_map,
1680 					     bool is_percpu, u64 flags)
1681 {
1682 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1683 	struct hlist_nulls_head *head;
1684 	unsigned long bflags;
1685 	struct htab_elem *l;
1686 	u32 hash, key_size;
1687 	struct bucket *b;
1688 	int ret;
1689 
1690 	key_size = map->key_size;
1691 
1692 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1693 	b = __select_bucket(htab, hash);
1694 	head = &b->head;
1695 
1696 	ret = htab_lock_bucket(b, &bflags);
1697 	if (ret)
1698 		return ret;
1699 
1700 	l = lookup_elem_raw(head, hash, key, key_size);
1701 	if (!l) {
1702 		ret = -ENOENT;
1703 		goto out_unlock;
1704 	}
1705 
1706 	if (is_percpu) {
1707 		u32 roundup_value_size = round_up(map->value_size, 8);
1708 		void __percpu *pptr;
1709 		int off = 0, cpu;
1710 
1711 		pptr = htab_elem_get_ptr(l, key_size);
1712 		for_each_possible_cpu(cpu) {
1713 			copy_map_value_long(&htab->map, value + off, per_cpu_ptr(pptr, cpu));
1714 			check_and_init_map_value(&htab->map, value + off);
1715 			off += roundup_value_size;
1716 		}
1717 	} else {
1718 		void *src = htab_elem_value(l, map->key_size);
1719 
1720 		if (flags & BPF_F_LOCK)
1721 			copy_map_value_locked(map, value, src, true);
1722 		else
1723 			copy_map_value(map, value, src);
1724 		/* Zeroing special fields in the temp buffer */
1725 		check_and_init_map_value(map, value);
1726 	}
1727 	hlist_nulls_del_rcu(&l->hash_node);
1728 
1729 out_unlock:
1730 	htab_unlock_bucket(b, bflags);
1731 
1732 	if (l) {
1733 		if (is_lru_map)
1734 			htab_lru_push_free(htab, l);
1735 		else
1736 			free_htab_elem(htab, l);
1737 	}
1738 
1739 	return ret;
1740 }
1741 
1742 static int htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
1743 					   void *value, u64 flags)
1744 {
1745 	return __htab_map_lookup_and_delete_elem(map, key, value, false, false,
1746 						 flags);
1747 }
1748 
1749 static int htab_percpu_map_lookup_and_delete_elem(struct bpf_map *map,
1750 						  void *key, void *value,
1751 						  u64 flags)
1752 {
1753 	return __htab_map_lookup_and_delete_elem(map, key, value, false, true,
1754 						 flags);
1755 }
1756 
1757 static int htab_lru_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
1758 					       void *value, u64 flags)
1759 {
1760 	return __htab_map_lookup_and_delete_elem(map, key, value, true, false,
1761 						 flags);
1762 }
1763 
1764 static int htab_lru_percpu_map_lookup_and_delete_elem(struct bpf_map *map,
1765 						      void *key, void *value,
1766 						      u64 flags)
1767 {
1768 	return __htab_map_lookup_and_delete_elem(map, key, value, true, true,
1769 						 flags);
1770 }
1771 
1772 static int
1773 __htab_map_lookup_and_delete_batch(struct bpf_map *map,
1774 				   const union bpf_attr *attr,
1775 				   union bpf_attr __user *uattr,
1776 				   bool do_delete, bool is_lru_map,
1777 				   bool is_percpu)
1778 {
1779 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1780 	void *keys = NULL, *values = NULL, *value, *dst_key, *dst_val;
1781 	void __user *uvalues = u64_to_user_ptr(attr->batch.values);
1782 	void __user *ukeys = u64_to_user_ptr(attr->batch.keys);
1783 	void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1784 	u32 batch, max_count, size, bucket_size, map_id;
1785 	u64 elem_map_flags, map_flags, allowed_flags;
1786 	u32 bucket_cnt, total, key_size, value_size;
1787 	struct htab_elem *node_to_free = NULL;
1788 	struct hlist_nulls_head *head;
1789 	struct hlist_nulls_node *n;
1790 	unsigned long flags = 0;
1791 	bool locked = false;
1792 	struct htab_elem *l;
1793 	struct bucket *b;
1794 	int ret = 0;
1795 
1796 	elem_map_flags = attr->batch.elem_flags;
1797 	allowed_flags = BPF_F_LOCK;
1798 	if (!do_delete && is_percpu)
1799 		allowed_flags |= BPF_F_CPU;
1800 	ret = bpf_map_check_op_flags(map, elem_map_flags, allowed_flags);
1801 	if (ret)
1802 		return ret;
1803 
1804 	map_flags = attr->batch.flags;
1805 	if (map_flags)
1806 		return -EINVAL;
1807 
1808 	max_count = attr->batch.count;
1809 	if (!max_count)
1810 		return 0;
1811 
1812 	if (put_user(0, &uattr->batch.count))
1813 		return -EFAULT;
1814 
1815 	batch = 0;
1816 	if (ubatch && copy_from_user(&batch, ubatch, sizeof(batch)))
1817 		return -EFAULT;
1818 
1819 	if (batch >= htab->n_buckets)
1820 		return -ENOENT;
1821 
1822 	key_size = htab->map.key_size;
1823 	value_size = htab->map.value_size;
1824 	size = round_up(value_size, 8);
1825 	if (is_percpu && !(elem_map_flags & BPF_F_CPU))
1826 		value_size = size * num_possible_cpus();
1827 	total = 0;
1828 	/* while experimenting with hash tables with sizes ranging from 10 to
1829 	 * 1000, it was observed that a bucket can have up to 5 entries.
1830 	 */
1831 	bucket_size = 5;
1832 
1833 alloc:
1834 	/* We cannot do copy_from_user or copy_to_user inside
1835 	 * the rcu_read_lock. Allocate enough space here.
1836 	 */
1837 	keys = kvmalloc_array(key_size, bucket_size, GFP_USER | __GFP_NOWARN);
1838 	values = kvmalloc_array(value_size, bucket_size, GFP_USER | __GFP_NOWARN);
1839 	if (!keys || !values) {
1840 		ret = -ENOMEM;
1841 		goto after_loop;
1842 	}
1843 
1844 again:
1845 	bpf_disable_instrumentation();
1846 	rcu_read_lock();
1847 again_nocopy:
1848 	dst_key = keys;
1849 	dst_val = values;
1850 	b = &htab->buckets[batch];
1851 	head = &b->head;
1852 	/* do not grab the lock unless need it (bucket_cnt > 0). */
1853 	if (locked) {
1854 		ret = htab_lock_bucket(b, &flags);
1855 		if (ret) {
1856 			rcu_read_unlock();
1857 			bpf_enable_instrumentation();
1858 			goto after_loop;
1859 		}
1860 	}
1861 
1862 	bucket_cnt = 0;
1863 	hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
1864 		bucket_cnt++;
1865 
1866 	if (bucket_cnt && !locked) {
1867 		locked = true;
1868 		goto again_nocopy;
1869 	}
1870 
1871 	if (bucket_cnt > (max_count - total)) {
1872 		if (total == 0)
1873 			ret = -ENOSPC;
1874 		/* Note that since bucket_cnt > 0 here, it is implicit
1875 		 * that the locked was grabbed, so release it.
1876 		 */
1877 		htab_unlock_bucket(b, flags);
1878 		rcu_read_unlock();
1879 		bpf_enable_instrumentation();
1880 		goto after_loop;
1881 	}
1882 
1883 	if (bucket_cnt > bucket_size) {
1884 		bucket_size = bucket_cnt;
1885 		/* Note that since bucket_cnt > 0 here, it is implicit
1886 		 * that the locked was grabbed, so release it.
1887 		 */
1888 		htab_unlock_bucket(b, flags);
1889 		rcu_read_unlock();
1890 		bpf_enable_instrumentation();
1891 		kvfree(keys);
1892 		kvfree(values);
1893 		goto alloc;
1894 	}
1895 
1896 	/* Next block is only safe to run if you have grabbed the lock */
1897 	if (!locked)
1898 		goto next_batch;
1899 
1900 	hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
1901 		memcpy(dst_key, l->key, key_size);
1902 
1903 		if (is_percpu) {
1904 			int off = 0, cpu;
1905 			void __percpu *pptr;
1906 
1907 			pptr = htab_elem_get_ptr(l, map->key_size);
1908 			if (elem_map_flags & BPF_F_CPU) {
1909 				cpu = elem_map_flags >> 32;
1910 				copy_map_value(&htab->map, dst_val, per_cpu_ptr(pptr, cpu));
1911 				check_and_init_map_value(&htab->map, dst_val);
1912 			} else {
1913 				for_each_possible_cpu(cpu) {
1914 					copy_map_value_long(&htab->map, dst_val + off,
1915 							    per_cpu_ptr(pptr, cpu));
1916 					check_and_init_map_value(&htab->map, dst_val + off);
1917 					off += size;
1918 				}
1919 			}
1920 		} else {
1921 			value = htab_elem_value(l, key_size);
1922 			if (is_fd_htab(htab)) {
1923 				struct bpf_map **inner_map = value;
1924 
1925 				 /* Actual value is the id of the inner map */
1926 				map_id = map->ops->map_fd_sys_lookup_elem(*inner_map);
1927 				value = &map_id;
1928 			}
1929 
1930 			if (elem_map_flags & BPF_F_LOCK)
1931 				copy_map_value_locked(map, dst_val, value,
1932 						      true);
1933 			else
1934 				copy_map_value(map, dst_val, value);
1935 			/* Zeroing special fields in the temp buffer */
1936 			check_and_init_map_value(map, dst_val);
1937 		}
1938 		if (do_delete) {
1939 			hlist_nulls_del_rcu(&l->hash_node);
1940 
1941 			/* bpf_lru_push_free() will acquire lru_lock, which
1942 			 * may cause deadlock. See comments in function
1943 			 * prealloc_lru_pop(). Let us do bpf_lru_push_free()
1944 			 * after releasing the bucket lock.
1945 			 *
1946 			 * For htab of maps, htab_put_fd_value() in
1947 			 * free_htab_elem() may acquire a spinlock with bucket
1948 			 * lock being held and it violates the lock rule, so
1949 			 * invoke free_htab_elem() after unlock as well.
1950 			 */
1951 			l->batch_flink = node_to_free;
1952 			node_to_free = l;
1953 		}
1954 		dst_key += key_size;
1955 		dst_val += value_size;
1956 	}
1957 
1958 	htab_unlock_bucket(b, flags);
1959 	locked = false;
1960 
1961 	while (node_to_free) {
1962 		l = node_to_free;
1963 		node_to_free = node_to_free->batch_flink;
1964 		if (is_lru_map)
1965 			htab_lru_push_free(htab, l);
1966 		else
1967 			free_htab_elem(htab, l);
1968 	}
1969 
1970 next_batch:
1971 	/* If we are not copying data, we can go to next bucket and avoid
1972 	 * unlocking the rcu.
1973 	 */
1974 	if (!bucket_cnt && (batch + 1 < htab->n_buckets)) {
1975 		batch++;
1976 		goto again_nocopy;
1977 	}
1978 
1979 	rcu_read_unlock();
1980 	bpf_enable_instrumentation();
1981 	if (bucket_cnt && (copy_to_user(ukeys + total * key_size, keys,
1982 	    key_size * bucket_cnt) ||
1983 	    copy_to_user(uvalues + total * value_size, values,
1984 	    value_size * bucket_cnt))) {
1985 		ret = -EFAULT;
1986 		goto after_loop;
1987 	}
1988 
1989 	total += bucket_cnt;
1990 	batch++;
1991 	if (batch >= htab->n_buckets) {
1992 		ret = -ENOENT;
1993 		goto after_loop;
1994 	}
1995 	goto again;
1996 
1997 after_loop:
1998 	if (ret == -EFAULT)
1999 		goto out;
2000 
2001 	/* copy # of entries and next batch */
2002 	ubatch = u64_to_user_ptr(attr->batch.out_batch);
2003 	if (copy_to_user(ubatch, &batch, sizeof(batch)) ||
2004 	    put_user(total, &uattr->batch.count))
2005 		ret = -EFAULT;
2006 
2007 out:
2008 	kvfree(keys);
2009 	kvfree(values);
2010 	return ret;
2011 }
2012 
2013 static int
2014 htab_percpu_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
2015 			     union bpf_attr __user *uattr)
2016 {
2017 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
2018 						  false, true);
2019 }
2020 
2021 static int
2022 htab_percpu_map_lookup_and_delete_batch(struct bpf_map *map,
2023 					const union bpf_attr *attr,
2024 					union bpf_attr __user *uattr)
2025 {
2026 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
2027 						  false, true);
2028 }
2029 
2030 static int
2031 htab_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
2032 		      union bpf_attr __user *uattr)
2033 {
2034 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
2035 						  false, false);
2036 }
2037 
2038 static int
2039 htab_map_lookup_and_delete_batch(struct bpf_map *map,
2040 				 const union bpf_attr *attr,
2041 				 union bpf_attr __user *uattr)
2042 {
2043 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
2044 						  false, false);
2045 }
2046 
2047 static int
2048 htab_lru_percpu_map_lookup_batch(struct bpf_map *map,
2049 				 const union bpf_attr *attr,
2050 				 union bpf_attr __user *uattr)
2051 {
2052 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
2053 						  true, true);
2054 }
2055 
2056 static int
2057 htab_lru_percpu_map_lookup_and_delete_batch(struct bpf_map *map,
2058 					    const union bpf_attr *attr,
2059 					    union bpf_attr __user *uattr)
2060 {
2061 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
2062 						  true, true);
2063 }
2064 
2065 static int
2066 htab_lru_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
2067 			  union bpf_attr __user *uattr)
2068 {
2069 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
2070 						  true, false);
2071 }
2072 
2073 static int
2074 htab_lru_map_lookup_and_delete_batch(struct bpf_map *map,
2075 				     const union bpf_attr *attr,
2076 				     union bpf_attr __user *uattr)
2077 {
2078 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
2079 						  true, false);
2080 }
2081 
2082 struct bpf_iter_seq_hash_map_info {
2083 	struct bpf_map *map;
2084 	struct bpf_htab *htab;
2085 	void *percpu_value_buf; // non-zero means percpu hash
2086 	u32 bucket_id;
2087 	u32 skip_elems;
2088 };
2089 
2090 static struct htab_elem *
2091 bpf_hash_map_seq_find_next(struct bpf_iter_seq_hash_map_info *info,
2092 			   struct htab_elem *prev_elem)
2093 {
2094 	const struct bpf_htab *htab = info->htab;
2095 	u32 skip_elems = info->skip_elems;
2096 	u32 bucket_id = info->bucket_id;
2097 	struct hlist_nulls_head *head;
2098 	struct hlist_nulls_node *n;
2099 	struct htab_elem *elem;
2100 	struct bucket *b;
2101 	u32 i, count;
2102 
2103 	if (bucket_id >= htab->n_buckets)
2104 		return NULL;
2105 
2106 	/* try to find next elem in the same bucket */
2107 	if (prev_elem) {
2108 		/* no update/deletion on this bucket, prev_elem should be still valid
2109 		 * and we won't skip elements.
2110 		 */
2111 		n = rcu_dereference_raw(hlist_nulls_next_rcu(&prev_elem->hash_node));
2112 		elem = hlist_nulls_entry_safe(n, struct htab_elem, hash_node);
2113 		if (elem)
2114 			return elem;
2115 
2116 		/* not found, unlock and go to the next bucket */
2117 		b = &htab->buckets[bucket_id++];
2118 		rcu_read_unlock();
2119 		skip_elems = 0;
2120 	}
2121 
2122 	for (i = bucket_id; i < htab->n_buckets; i++) {
2123 		b = &htab->buckets[i];
2124 		rcu_read_lock();
2125 
2126 		count = 0;
2127 		head = &b->head;
2128 		hlist_nulls_for_each_entry_rcu(elem, n, head, hash_node) {
2129 			if (count >= skip_elems) {
2130 				info->bucket_id = i;
2131 				info->skip_elems = count;
2132 				return elem;
2133 			}
2134 			count++;
2135 		}
2136 
2137 		rcu_read_unlock();
2138 		skip_elems = 0;
2139 	}
2140 
2141 	info->bucket_id = i;
2142 	info->skip_elems = 0;
2143 	return NULL;
2144 }
2145 
2146 static void *bpf_hash_map_seq_start(struct seq_file *seq, loff_t *pos)
2147 {
2148 	struct bpf_iter_seq_hash_map_info *info = seq->private;
2149 	struct htab_elem *elem;
2150 
2151 	elem = bpf_hash_map_seq_find_next(info, NULL);
2152 	if (!elem)
2153 		return NULL;
2154 
2155 	if (*pos == 0)
2156 		++*pos;
2157 	return elem;
2158 }
2159 
2160 static void *bpf_hash_map_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2161 {
2162 	struct bpf_iter_seq_hash_map_info *info = seq->private;
2163 
2164 	++*pos;
2165 	++info->skip_elems;
2166 	return bpf_hash_map_seq_find_next(info, v);
2167 }
2168 
2169 static int __bpf_hash_map_seq_show(struct seq_file *seq, struct htab_elem *elem)
2170 {
2171 	struct bpf_iter_seq_hash_map_info *info = seq->private;
2172 	struct bpf_iter__bpf_map_elem ctx = {};
2173 	struct bpf_map *map = info->map;
2174 	struct bpf_iter_meta meta;
2175 	int ret = 0, off = 0, cpu;
2176 	u32 roundup_value_size;
2177 	struct bpf_prog *prog;
2178 	void __percpu *pptr;
2179 
2180 	meta.seq = seq;
2181 	prog = bpf_iter_get_info(&meta, elem == NULL);
2182 	if (prog) {
2183 		ctx.meta = &meta;
2184 		ctx.map = info->map;
2185 		if (elem) {
2186 			ctx.key = elem->key;
2187 			if (!info->percpu_value_buf) {
2188 				ctx.value = htab_elem_value(elem, map->key_size);
2189 			} else {
2190 				roundup_value_size = round_up(map->value_size, 8);
2191 				pptr = htab_elem_get_ptr(elem, map->key_size);
2192 				for_each_possible_cpu(cpu) {
2193 					copy_map_value_long(map, info->percpu_value_buf + off,
2194 							    per_cpu_ptr(pptr, cpu));
2195 					check_and_init_map_value(map, info->percpu_value_buf + off);
2196 					off += roundup_value_size;
2197 				}
2198 				ctx.value = info->percpu_value_buf;
2199 			}
2200 		}
2201 		ret = bpf_iter_run_prog(prog, &ctx);
2202 	}
2203 
2204 	return ret;
2205 }
2206 
2207 static int bpf_hash_map_seq_show(struct seq_file *seq, void *v)
2208 {
2209 	return __bpf_hash_map_seq_show(seq, v);
2210 }
2211 
2212 static void bpf_hash_map_seq_stop(struct seq_file *seq, void *v)
2213 {
2214 	if (!v)
2215 		(void)__bpf_hash_map_seq_show(seq, NULL);
2216 	else
2217 		rcu_read_unlock();
2218 }
2219 
2220 static int bpf_iter_init_hash_map(void *priv_data,
2221 				  struct bpf_iter_aux_info *aux)
2222 {
2223 	struct bpf_iter_seq_hash_map_info *seq_info = priv_data;
2224 	struct bpf_map *map = aux->map;
2225 	void *value_buf;
2226 	u32 buf_size;
2227 
2228 	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
2229 	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
2230 		buf_size = round_up(map->value_size, 8) * num_possible_cpus();
2231 		value_buf = kmalloc(buf_size, GFP_USER | __GFP_NOWARN);
2232 		if (!value_buf)
2233 			return -ENOMEM;
2234 
2235 		seq_info->percpu_value_buf = value_buf;
2236 	}
2237 
2238 	bpf_map_inc_with_uref(map);
2239 	seq_info->map = map;
2240 	seq_info->htab = container_of(map, struct bpf_htab, map);
2241 	return 0;
2242 }
2243 
2244 static void bpf_iter_fini_hash_map(void *priv_data)
2245 {
2246 	struct bpf_iter_seq_hash_map_info *seq_info = priv_data;
2247 
2248 	bpf_map_put_with_uref(seq_info->map);
2249 	kfree(seq_info->percpu_value_buf);
2250 }
2251 
2252 static const struct seq_operations bpf_hash_map_seq_ops = {
2253 	.start	= bpf_hash_map_seq_start,
2254 	.next	= bpf_hash_map_seq_next,
2255 	.stop	= bpf_hash_map_seq_stop,
2256 	.show	= bpf_hash_map_seq_show,
2257 };
2258 
2259 static const struct bpf_iter_seq_info iter_seq_info = {
2260 	.seq_ops		= &bpf_hash_map_seq_ops,
2261 	.init_seq_private	= bpf_iter_init_hash_map,
2262 	.fini_seq_private	= bpf_iter_fini_hash_map,
2263 	.seq_priv_size		= sizeof(struct bpf_iter_seq_hash_map_info),
2264 };
2265 
2266 static long bpf_for_each_hash_elem(struct bpf_map *map, bpf_callback_t callback_fn,
2267 				   void *callback_ctx, u64 flags)
2268 {
2269 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2270 	struct hlist_nulls_head *head;
2271 	struct hlist_nulls_node *n;
2272 	struct htab_elem *elem;
2273 	int i, num_elems = 0;
2274 	void __percpu *pptr;
2275 	struct bucket *b;
2276 	void *key, *val;
2277 	bool is_percpu;
2278 	u64 ret = 0;
2279 
2280 	cant_migrate();
2281 
2282 	if (flags != 0)
2283 		return -EINVAL;
2284 
2285 	is_percpu = htab_is_percpu(htab);
2286 
2287 	/* migration has been disabled, so percpu value prepared here will be
2288 	 * the same as the one seen by the bpf program with
2289 	 * bpf_map_lookup_elem().
2290 	 */
2291 	for (i = 0; i < htab->n_buckets; i++) {
2292 		b = &htab->buckets[i];
2293 		rcu_read_lock();
2294 		head = &b->head;
2295 		hlist_nulls_for_each_entry_safe(elem, n, head, hash_node) {
2296 			key = elem->key;
2297 			if (is_percpu) {
2298 				/* current cpu value for percpu map */
2299 				pptr = htab_elem_get_ptr(elem, map->key_size);
2300 				val = this_cpu_ptr(pptr);
2301 			} else {
2302 				val = htab_elem_value(elem, map->key_size);
2303 			}
2304 			num_elems++;
2305 			ret = callback_fn((u64)(long)map, (u64)(long)key,
2306 					  (u64)(long)val, (u64)(long)callback_ctx, 0);
2307 			/* return value: 0 - continue, 1 - stop and return */
2308 			if (ret) {
2309 				rcu_read_unlock();
2310 				goto out;
2311 			}
2312 		}
2313 		rcu_read_unlock();
2314 	}
2315 out:
2316 	return num_elems;
2317 }
2318 
2319 static u64 htab_map_mem_usage(const struct bpf_map *map)
2320 {
2321 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2322 	u32 value_size = round_up(htab->map.value_size, 8);
2323 	bool prealloc = htab_is_prealloc(htab);
2324 	bool percpu = htab_is_percpu(htab);
2325 	bool lru = htab_is_lru(htab);
2326 	u64 num_entries, usage;
2327 
2328 	usage = sizeof(struct bpf_htab) +
2329 		sizeof(struct bucket) * htab->n_buckets;
2330 
2331 	if (prealloc) {
2332 		num_entries = map->max_entries;
2333 		if (htab_has_extra_elems(htab))
2334 			num_entries += num_possible_cpus();
2335 
2336 		usage += htab->elem_size * num_entries;
2337 
2338 		if (percpu)
2339 			usage += value_size * num_possible_cpus() * num_entries;
2340 		else if (!lru)
2341 			usage += sizeof(struct htab_elem *) * num_possible_cpus();
2342 	} else {
2343 #define LLIST_NODE_SZ sizeof(struct llist_node)
2344 
2345 		num_entries = htab->use_percpu_counter ?
2346 					  percpu_counter_sum(&htab->pcount) :
2347 					  atomic_read(&htab->count);
2348 		usage += (htab->elem_size + LLIST_NODE_SZ) * num_entries;
2349 		if (percpu) {
2350 			usage += (LLIST_NODE_SZ + sizeof(void *)) * num_entries;
2351 			usage += value_size * num_possible_cpus() * num_entries;
2352 		}
2353 	}
2354 	return usage;
2355 }
2356 
2357 BTF_ID_LIST_SINGLE(htab_map_btf_ids, struct, bpf_htab)
2358 const struct bpf_map_ops htab_map_ops = {
2359 	.map_meta_equal = bpf_map_meta_equal,
2360 	.map_alloc_check = htab_map_alloc_check,
2361 	.map_alloc = htab_map_alloc,
2362 	.map_free = htab_map_free,
2363 	.map_get_next_key = htab_map_get_next_key,
2364 	.map_release_uref = htab_map_free_internal_structs,
2365 	.map_lookup_elem = htab_map_lookup_elem,
2366 	.map_lookup_and_delete_elem = htab_map_lookup_and_delete_elem,
2367 	.map_update_elem = htab_map_update_elem,
2368 	.map_delete_elem = htab_map_delete_elem,
2369 	.map_gen_lookup = htab_map_gen_lookup,
2370 	.map_seq_show_elem = htab_map_seq_show_elem,
2371 	.map_set_for_each_callback_args = map_set_for_each_callback_args,
2372 	.map_for_each_callback = bpf_for_each_hash_elem,
2373 	.map_check_btf = htab_map_check_btf,
2374 	.map_mem_usage = htab_map_mem_usage,
2375 	BATCH_OPS(htab),
2376 	.map_btf_id = &htab_map_btf_ids[0],
2377 	.iter_seq_info = &iter_seq_info,
2378 };
2379 
2380 const struct bpf_map_ops htab_lru_map_ops = {
2381 	.map_meta_equal = bpf_map_meta_equal,
2382 	.map_alloc_check = htab_map_alloc_check,
2383 	.map_alloc = htab_map_alloc,
2384 	.map_free = htab_map_free,
2385 	.map_get_next_key = htab_map_get_next_key,
2386 	.map_release_uref = htab_map_free_internal_structs,
2387 	.map_lookup_elem = htab_lru_map_lookup_elem,
2388 	.map_lookup_and_delete_elem = htab_lru_map_lookup_and_delete_elem,
2389 	.map_lookup_elem_sys_only = htab_lru_map_lookup_elem_sys,
2390 	.map_update_elem = htab_lru_map_update_elem,
2391 	.map_delete_elem = htab_lru_map_delete_elem,
2392 	.map_gen_lookup = htab_lru_map_gen_lookup,
2393 	.map_seq_show_elem = htab_map_seq_show_elem,
2394 	.map_set_for_each_callback_args = map_set_for_each_callback_args,
2395 	.map_for_each_callback = bpf_for_each_hash_elem,
2396 	.map_check_btf = htab_map_check_btf,
2397 	.map_mem_usage = htab_map_mem_usage,
2398 	BATCH_OPS(htab_lru),
2399 	.map_btf_id = &htab_map_btf_ids[0],
2400 	.iter_seq_info = &iter_seq_info,
2401 };
2402 
2403 /* Called from eBPF program */
2404 static void *htab_percpu_map_lookup_elem(struct bpf_map *map, void *key)
2405 {
2406 	struct htab_elem *l = __htab_map_lookup_elem(map, key);
2407 
2408 	if (l)
2409 		return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size));
2410 	else
2411 		return NULL;
2412 }
2413 
2414 /* inline bpf_map_lookup_elem() call for per-CPU hashmap */
2415 static int htab_percpu_map_gen_lookup(struct bpf_map *map, struct bpf_insn *insn_buf)
2416 {
2417 	struct bpf_insn *insn = insn_buf;
2418 
2419 	if (!bpf_jit_supports_percpu_insn())
2420 		return -EOPNOTSUPP;
2421 
2422 	BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
2423 		     (void *(*)(struct bpf_map *map, void *key))NULL));
2424 	*insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
2425 	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 3);
2426 	*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_0,
2427 				offsetof(struct htab_elem, key) + roundup(map->key_size, 8));
2428 	*insn++ = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_0, 0);
2429 	*insn++ = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
2430 
2431 	return insn - insn_buf;
2432 }
2433 
2434 static void *htab_percpu_map_lookup_percpu_elem(struct bpf_map *map, void *key, u32 cpu)
2435 {
2436 	struct htab_elem *l;
2437 
2438 	if (cpu >= nr_cpu_ids)
2439 		return NULL;
2440 
2441 	l = __htab_map_lookup_elem(map, key);
2442 	if (l)
2443 		return per_cpu_ptr(htab_elem_get_ptr(l, map->key_size), cpu);
2444 	else
2445 		return NULL;
2446 }
2447 
2448 static void *htab_lru_percpu_map_lookup_elem(struct bpf_map *map, void *key)
2449 {
2450 	struct htab_elem *l = __htab_map_lookup_elem(map, key);
2451 
2452 	if (l) {
2453 		bpf_lru_node_set_ref(&l->lru_node);
2454 		return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size));
2455 	}
2456 
2457 	return NULL;
2458 }
2459 
2460 static void *htab_lru_percpu_map_lookup_percpu_elem(struct bpf_map *map, void *key, u32 cpu)
2461 {
2462 	struct htab_elem *l;
2463 
2464 	if (cpu >= nr_cpu_ids)
2465 		return NULL;
2466 
2467 	l = __htab_map_lookup_elem(map, key);
2468 	if (l) {
2469 		bpf_lru_node_set_ref(&l->lru_node);
2470 		return per_cpu_ptr(htab_elem_get_ptr(l, map->key_size), cpu);
2471 	}
2472 
2473 	return NULL;
2474 }
2475 
2476 int bpf_percpu_hash_copy(struct bpf_map *map, void *key, void *value, u64 map_flags)
2477 {
2478 	struct htab_elem *l;
2479 	void __percpu *pptr;
2480 	int ret = -ENOENT;
2481 	int cpu, off = 0;
2482 	u32 size;
2483 
2484 	/* per_cpu areas are zero-filled and bpf programs can only
2485 	 * access 'value_size' of them, so copying rounded areas
2486 	 * will not leak any kernel data
2487 	 */
2488 	size = round_up(map->value_size, 8);
2489 	rcu_read_lock();
2490 	l = __htab_map_lookup_elem(map, key);
2491 	if (!l)
2492 		goto out;
2493 	ret = 0;
2494 	/* We do not mark LRU map element here in order to not mess up
2495 	 * eviction heuristics when user space does a map walk.
2496 	 */
2497 	pptr = htab_elem_get_ptr(l, map->key_size);
2498 	if (map_flags & BPF_F_CPU) {
2499 		cpu = map_flags >> 32;
2500 		copy_map_value(map, value, per_cpu_ptr(pptr, cpu));
2501 		check_and_init_map_value(map, value);
2502 		goto out;
2503 	}
2504 	for_each_possible_cpu(cpu) {
2505 		copy_map_value_long(map, value + off, per_cpu_ptr(pptr, cpu));
2506 		check_and_init_map_value(map, value + off);
2507 		off += size;
2508 	}
2509 out:
2510 	rcu_read_unlock();
2511 	return ret;
2512 }
2513 
2514 int bpf_percpu_hash_update(struct bpf_map *map, void *key, void *value,
2515 			   u64 map_flags)
2516 {
2517 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2518 	int ret;
2519 
2520 	rcu_read_lock();
2521 	if (htab_is_lru(htab))
2522 		ret = __htab_lru_percpu_map_update_elem(map, key, value,
2523 							map_flags, true);
2524 	else
2525 		ret = htab_map_update_elem_in_place(map, key, value, map_flags,
2526 						    true, true);
2527 	rcu_read_unlock();
2528 
2529 	return ret;
2530 }
2531 
2532 static void htab_percpu_map_seq_show_elem(struct bpf_map *map, void *key,
2533 					  struct seq_file *m)
2534 {
2535 	struct htab_elem *l;
2536 	void __percpu *pptr;
2537 	int cpu;
2538 
2539 	rcu_read_lock();
2540 
2541 	l = __htab_map_lookup_elem(map, key);
2542 	if (!l) {
2543 		rcu_read_unlock();
2544 		return;
2545 	}
2546 
2547 	btf_type_seq_show(map->btf, map->btf_key_type_id, key, m);
2548 	seq_puts(m, ": {\n");
2549 	pptr = htab_elem_get_ptr(l, map->key_size);
2550 	for_each_possible_cpu(cpu) {
2551 		seq_printf(m, "\tcpu%d: ", cpu);
2552 		btf_type_seq_show(map->btf, map->btf_value_type_id,
2553 				  per_cpu_ptr(pptr, cpu), m);
2554 		seq_putc(m, '\n');
2555 	}
2556 	seq_puts(m, "}\n");
2557 
2558 	rcu_read_unlock();
2559 }
2560 
2561 const struct bpf_map_ops htab_percpu_map_ops = {
2562 	.map_meta_equal = bpf_map_meta_equal,
2563 	.map_alloc_check = htab_map_alloc_check,
2564 	.map_alloc = htab_map_alloc,
2565 	.map_free = htab_map_free,
2566 	.map_get_next_key = htab_map_get_next_key,
2567 	.map_lookup_elem = htab_percpu_map_lookup_elem,
2568 	.map_gen_lookup = htab_percpu_map_gen_lookup,
2569 	.map_lookup_and_delete_elem = htab_percpu_map_lookup_and_delete_elem,
2570 	.map_update_elem = htab_percpu_map_update_elem,
2571 	.map_delete_elem = htab_map_delete_elem,
2572 	.map_lookup_percpu_elem = htab_percpu_map_lookup_percpu_elem,
2573 	.map_seq_show_elem = htab_percpu_map_seq_show_elem,
2574 	.map_set_for_each_callback_args = map_set_for_each_callback_args,
2575 	.map_for_each_callback = bpf_for_each_hash_elem,
2576 	.map_check_btf = htab_map_check_btf,
2577 	.map_mem_usage = htab_map_mem_usage,
2578 	BATCH_OPS(htab_percpu),
2579 	.map_btf_id = &htab_map_btf_ids[0],
2580 	.iter_seq_info = &iter_seq_info,
2581 };
2582 
2583 const struct bpf_map_ops htab_lru_percpu_map_ops = {
2584 	.map_meta_equal = bpf_map_meta_equal,
2585 	.map_alloc_check = htab_map_alloc_check,
2586 	.map_alloc = htab_map_alloc,
2587 	.map_free = htab_map_free,
2588 	.map_get_next_key = htab_map_get_next_key,
2589 	.map_lookup_elem = htab_lru_percpu_map_lookup_elem,
2590 	.map_lookup_and_delete_elem = htab_lru_percpu_map_lookup_and_delete_elem,
2591 	.map_update_elem = htab_lru_percpu_map_update_elem,
2592 	.map_delete_elem = htab_lru_map_delete_elem,
2593 	.map_lookup_percpu_elem = htab_lru_percpu_map_lookup_percpu_elem,
2594 	.map_seq_show_elem = htab_percpu_map_seq_show_elem,
2595 	.map_set_for_each_callback_args = map_set_for_each_callback_args,
2596 	.map_for_each_callback = bpf_for_each_hash_elem,
2597 	.map_check_btf = htab_map_check_btf,
2598 	.map_mem_usage = htab_map_mem_usage,
2599 	BATCH_OPS(htab_lru_percpu),
2600 	.map_btf_id = &htab_map_btf_ids[0],
2601 	.iter_seq_info = &iter_seq_info,
2602 };
2603 
2604 static int fd_htab_map_alloc_check(union bpf_attr *attr)
2605 {
2606 	if (attr->value_size != sizeof(u32))
2607 		return -EINVAL;
2608 	return htab_map_alloc_check(attr);
2609 }
2610 
2611 static void fd_htab_map_free(struct bpf_map *map)
2612 {
2613 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2614 	struct hlist_nulls_node *n;
2615 	struct hlist_nulls_head *head;
2616 	struct htab_elem *l;
2617 	int i;
2618 
2619 	for (i = 0; i < htab->n_buckets; i++) {
2620 		head = select_bucket(htab, i);
2621 
2622 		hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
2623 			void *ptr = fd_htab_map_get_ptr(map, l);
2624 
2625 			map->ops->map_fd_put_ptr(map, ptr, false);
2626 		}
2627 	}
2628 
2629 	htab_map_free(map);
2630 }
2631 
2632 /* only called from syscall */
2633 int bpf_fd_htab_map_lookup_elem(struct bpf_map *map, void *key, u32 *value)
2634 {
2635 	void **ptr;
2636 	int ret = 0;
2637 
2638 	if (!map->ops->map_fd_sys_lookup_elem)
2639 		return -ENOTSUPP;
2640 
2641 	rcu_read_lock();
2642 	ptr = htab_map_lookup_elem(map, key);
2643 	if (ptr)
2644 		*value = map->ops->map_fd_sys_lookup_elem(READ_ONCE(*ptr));
2645 	else
2646 		ret = -ENOENT;
2647 	rcu_read_unlock();
2648 
2649 	return ret;
2650 }
2651 
2652 /* Only called from syscall */
2653 int bpf_fd_htab_map_update_elem(struct bpf_map *map, struct file *map_file,
2654 				void *key, void *value, u64 map_flags)
2655 {
2656 	void *ptr;
2657 	int ret;
2658 
2659 	ptr = map->ops->map_fd_get_ptr(map, map_file, *(int *)value);
2660 	if (IS_ERR(ptr))
2661 		return PTR_ERR(ptr);
2662 
2663 	/* The htab bucket lock is always held during update operations in fd
2664 	 * htab map, and the following rcu_read_lock() is only used to avoid
2665 	 * the WARN_ON_ONCE in htab_map_update_elem_in_place().
2666 	 */
2667 	rcu_read_lock();
2668 	ret = htab_map_update_elem_in_place(map, key, &ptr, map_flags, false, false);
2669 	rcu_read_unlock();
2670 	if (ret)
2671 		map->ops->map_fd_put_ptr(map, ptr, false);
2672 
2673 	return ret;
2674 }
2675 
2676 static struct bpf_map *htab_of_map_alloc(union bpf_attr *attr)
2677 {
2678 	struct bpf_map *map, *inner_map_meta;
2679 
2680 	inner_map_meta = bpf_map_meta_alloc(attr->inner_map_fd);
2681 	if (IS_ERR(inner_map_meta))
2682 		return inner_map_meta;
2683 
2684 	map = htab_map_alloc(attr);
2685 	if (IS_ERR(map)) {
2686 		bpf_map_meta_free(inner_map_meta);
2687 		return map;
2688 	}
2689 
2690 	map->inner_map_meta = inner_map_meta;
2691 
2692 	return map;
2693 }
2694 
2695 static void *htab_of_map_lookup_elem(struct bpf_map *map, void *key)
2696 {
2697 	struct bpf_map **inner_map  = htab_map_lookup_elem(map, key);
2698 
2699 	if (!inner_map)
2700 		return NULL;
2701 
2702 	return READ_ONCE(*inner_map);
2703 }
2704 
2705 static int htab_of_map_gen_lookup(struct bpf_map *map,
2706 				  struct bpf_insn *insn_buf)
2707 {
2708 	struct bpf_insn *insn = insn_buf;
2709 	const int ret = BPF_REG_0;
2710 
2711 	BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
2712 		     (void *(*)(struct bpf_map *map, void *key))NULL));
2713 	*insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
2714 	*insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 2);
2715 	*insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
2716 				offsetof(struct htab_elem, key) +
2717 				round_up(map->key_size, 8));
2718 	*insn++ = BPF_LDX_MEM(BPF_DW, ret, ret, 0);
2719 
2720 	return insn - insn_buf;
2721 }
2722 
2723 static void htab_of_map_free(struct bpf_map *map)
2724 {
2725 	bpf_map_meta_free(map->inner_map_meta);
2726 	fd_htab_map_free(map);
2727 }
2728 
2729 const struct bpf_map_ops htab_of_maps_map_ops = {
2730 	.map_alloc_check = fd_htab_map_alloc_check,
2731 	.map_alloc = htab_of_map_alloc,
2732 	.map_free = htab_of_map_free,
2733 	.map_get_next_key = htab_map_get_next_key,
2734 	.map_lookup_elem = htab_of_map_lookup_elem,
2735 	.map_delete_elem = htab_map_delete_elem,
2736 	.map_fd_get_ptr = bpf_map_fd_get_ptr,
2737 	.map_fd_put_ptr = bpf_map_fd_put_ptr,
2738 	.map_fd_sys_lookup_elem = bpf_map_fd_sys_lookup_elem,
2739 	.map_gen_lookup = htab_of_map_gen_lookup,
2740 	.map_check_btf = map_check_no_btf,
2741 	.map_mem_usage = htab_map_mem_usage,
2742 	BATCH_OPS(htab),
2743 	.map_btf_id = &htab_map_btf_ids[0],
2744 };
2745 
2746 struct rhtab_elem {
2747 	struct rhash_head node;
2748 	/* key bytes, then value bytes follow */
2749 	u8 data[] __aligned(8);
2750 };
2751 
2752 struct bpf_rhtab {
2753 	struct bpf_map map;
2754 	struct rhashtable ht;
2755 	struct bpf_mem_alloc ma;
2756 	u32 elem_size;
2757 	bool freeing_internal;
2758 };
2759 
2760 static const struct rhashtable_params rhtab_params = {
2761 	.head_offset = offsetof(struct rhtab_elem, node),
2762 	.key_offset  = offsetof(struct rhtab_elem, data),
2763 };
2764 
2765 static inline void *rhtab_elem_value(struct rhtab_elem *l, u32 key_size)
2766 {
2767 	return l->data + round_up(key_size, 8);
2768 }
2769 
2770 /* Specialize hash function and objcmp for long sized key */
2771 static __always_inline int rhtab_key_cmp_long(struct rhashtable_compare_arg *arg,
2772 					      const void *ptr)
2773 {
2774 	const unsigned long key1 = *(const unsigned long *)arg->key;
2775 	const struct rhtab_elem *key2 = ptr;
2776 
2777 	return key1 != *(const unsigned long *)key2->data;
2778 }
2779 
2780 static __always_inline u32 rhtab_hashfn_long(const void *data, u32 len, u32 seed)
2781 {
2782 	u64 k = *(const unsigned long *)data;
2783 
2784 	return (u32)(k ^ (k >> 32)) ^ seed;
2785 }
2786 
2787 static const struct rhashtable_params rhtab_params_long = {
2788 	.head_offset = offsetof(struct rhtab_elem, node),
2789 	.key_offset  = offsetof(struct rhtab_elem, data),
2790 	.key_len     = sizeof(long),
2791 	.hashfn      = rhtab_hashfn_long,
2792 	.obj_cmpfn   = rhtab_key_cmp_long,
2793 };
2794 
2795 static struct bpf_map *rhtab_map_alloc(union bpf_attr *attr)
2796 {
2797 	struct rhashtable_params params;
2798 	struct bpf_rhtab *rhtab;
2799 	int err = 0;
2800 
2801 	rhtab = bpf_map_area_alloc(sizeof(*rhtab), NUMA_NO_NODE);
2802 	if (!rhtab)
2803 		return ERR_PTR(-ENOMEM);
2804 
2805 	bpf_map_init_from_attr(&rhtab->map, attr);
2806 
2807 	if (rhtab->map.max_entries > 1UL << 31) {
2808 		err = -E2BIG;
2809 		goto free_rhtab;
2810 	}
2811 
2812 	rhtab->elem_size = sizeof(struct rhtab_elem) + round_up(rhtab->map.key_size, 8) +
2813 			   round_up(rhtab->map.value_size, 8);
2814 
2815 	params = rhtab_params;
2816 	params.key_len = rhtab->map.key_size;
2817 	params.nelem_hint = (u32)attr->map_extra;
2818 	params.automatic_shrinking = true;
2819 
2820 	if (rhtab->map.key_size == sizeof(long)) {
2821 		params.hashfn = rhtab_hashfn_long;
2822 		params.obj_cmpfn = rhtab_key_cmp_long;
2823 	}
2824 
2825 	err = rhashtable_init(&rhtab->ht, &params);
2826 	if (err)
2827 		goto free_rhtab;
2828 
2829 	/* Set max_elems after rhashtable_init() since init zeroes the struct */
2830 	rhtab->ht.max_elems = rhtab->map.max_entries;
2831 
2832 	err = bpf_mem_alloc_init(&rhtab->ma, rhtab->elem_size, false);
2833 	if (err)
2834 		goto destroy_rhtab;
2835 
2836 	return &rhtab->map;
2837 
2838 destroy_rhtab:
2839 	rhashtable_destroy(&rhtab->ht);
2840 free_rhtab:
2841 	bpf_map_area_free(rhtab);
2842 	return ERR_PTR(err);
2843 }
2844 
2845 static int rhtab_map_alloc_check(union bpf_attr *attr)
2846 {
2847 	if (!(attr->map_flags & BPF_F_NO_PREALLOC))
2848 		return -EINVAL;
2849 
2850 	if (attr->map_flags & BPF_F_ZERO_SEED)
2851 		return -EINVAL;
2852 
2853 	if (attr->key_size > U16_MAX)
2854 		return -E2BIG;
2855 
2856 	if (attr->map_extra >> 32)
2857 		return -EINVAL;
2858 
2859 	if ((u32)attr->map_extra > U16_MAX)
2860 		return -E2BIG;
2861 
2862 	if ((u32)attr->map_extra > attr->max_entries)
2863 		return -EINVAL;
2864 
2865 	return htab_map_alloc_check(attr);
2866 }
2867 
2868 static void rhtab_check_and_free_fields(struct bpf_rhtab *rhtab,
2869 					struct rhtab_elem *elem)
2870 {
2871 	if (IS_ERR_OR_NULL(rhtab->map.record))
2872 		return;
2873 
2874 	bpf_obj_free_fields(rhtab->map.record,
2875 			    rhtab_elem_value(elem, rhtab->map.key_size));
2876 }
2877 
2878 static void rhtab_mem_dtor(void *obj, void *ctx)
2879 {
2880 	struct htab_btf_record *hrec = ctx;
2881 	struct rhtab_elem *elem = obj;
2882 
2883 	if (IS_ERR_OR_NULL(hrec->record))
2884 		return;
2885 
2886 	bpf_obj_free_fields(hrec->record,
2887 			    rhtab_elem_value(elem, hrec->key_size));
2888 }
2889 
2890 static void rhtab_free_elem(void *ptr, void *arg)
2891 {
2892 	struct bpf_rhtab *rhtab = arg;
2893 	struct rhtab_elem *elem = ptr;
2894 
2895 	bpf_map_free_internal_structs(&rhtab->map, rhtab_elem_value(elem, rhtab->map.key_size));
2896 	bpf_mem_cache_free_rcu(&rhtab->ma, elem);
2897 }
2898 
2899 static void rhtab_map_free(struct bpf_map *map)
2900 {
2901 	struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map);
2902 
2903 	rhashtable_free_and_destroy(&rhtab->ht, rhtab_free_elem, rhtab);
2904 	bpf_mem_alloc_destroy(&rhtab->ma);
2905 	bpf_map_area_free(rhtab);
2906 }
2907 
2908 static void *rhtab_lookup_elem(struct bpf_map *map, void *key)
2909 {
2910 	struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map);
2911 
2912 	/* Hold RCU lock in case sleepable program calls via gen_lookup */
2913 	guard(rcu)();
2914 
2915 	if (map->key_size == sizeof(long))
2916 		return rhashtable_lookup_likely(&rhtab->ht, key, rhtab_params_long);
2917 
2918 	return rhashtable_lookup_likely(&rhtab->ht, key, rhtab_params);
2919 }
2920 
2921 static void *rhtab_map_lookup_elem(struct bpf_map *map, void *key) __must_hold(RCU)
2922 {
2923 	struct rhtab_elem *l;
2924 
2925 	l = rhtab_lookup_elem(map, key);
2926 	return l ? rhtab_elem_value(l, map->key_size) : NULL;
2927 }
2928 
2929 static void rhtab_read_elem_value(struct bpf_map *map, void *dst, struct rhtab_elem *elem,
2930 				  u64 flags)
2931 {
2932 	void *src = rhtab_elem_value(elem, map->key_size);
2933 
2934 	if (flags & BPF_F_LOCK)
2935 		copy_map_value_locked(map, dst, src, true);
2936 	else
2937 		copy_map_value(map, dst, src);
2938 }
2939 
2940 static int rhtab_delete_elem(struct bpf_rhtab *rhtab, struct rhtab_elem *elem, void *copy,
2941 			     u64 flags)
2942 {
2943 	int err;
2944 
2945 	/*
2946 	 * disable_instrumentation() mitigates the deadlock for programs running in NMI context.
2947 	 * rhashtable locks bucket with local_irq_save(). Only NMI programs may reenter
2948 	 * rhashtable code, bpf_disable_instrumentation() disables programs running in NMI, except
2949 	 * raw tracepoints, which we don't have in rhashtable.
2950 	 */
2951 	bpf_disable_instrumentation();
2952 
2953 	if (rhtab->map.key_size == sizeof(long))
2954 		err = rhashtable_remove_fast(&rhtab->ht, &elem->node, rhtab_params_long);
2955 	else
2956 		err = rhashtable_remove_fast(&rhtab->ht, &elem->node, rhtab_params);
2957 
2958 	bpf_enable_instrumentation();
2959 
2960 	if (err)
2961 		return err;
2962 
2963 	if (copy) {
2964 		rhtab_read_elem_value(&rhtab->map, copy, elem, flags);
2965 		check_and_init_map_value(&rhtab->map, copy);
2966 	}
2967 	/* Release internal structs: kptr, bpf_timer, task_work, wq */
2968 	rhtab_check_and_free_fields(rhtab, elem);
2969 	bpf_mem_cache_free_rcu(&rhtab->ma, elem);
2970 	return 0;
2971 }
2972 
2973 
2974 static long rhtab_map_delete_elem(struct bpf_map *map, void *key)
2975 {
2976 	struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map);
2977 	struct rhtab_elem *elem;
2978 
2979 	guard(rcu)();
2980 
2981 	elem = rhtab_lookup_elem(map, key);
2982 	if (!elem)
2983 		return -ENOENT;
2984 
2985 	return rhtab_delete_elem(rhtab, elem, NULL, 0);
2986 }
2987 
2988 static int rhtab_map_lookup_and_delete_elem(struct bpf_map *map, void *key, void *value, u64 flags)
2989 {
2990 	struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map);
2991 	struct rhtab_elem *elem;
2992 	int err;
2993 
2994 	err = bpf_map_check_op_flags(map, flags, BPF_F_LOCK);
2995 	if (err)
2996 		return err;
2997 
2998 	guard(rcu)();
2999 
3000 	elem = rhtab_lookup_elem(map, key);
3001 	if (!elem)
3002 		return -ENOENT;
3003 
3004 	return rhtab_delete_elem(rhtab, elem, value, flags);
3005 }
3006 
3007 static long rhtab_map_update_existing(struct bpf_map *map, struct rhtab_elem *elem, void *value,
3008 				      u64 map_flags)
3009 {
3010 	struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map);
3011 	void *old_val = rhtab_elem_value(elem, map->key_size);
3012 
3013 	if (map_flags & BPF_NOEXIST)
3014 		return -EEXIST;
3015 
3016 	if (map_flags & BPF_F_LOCK)
3017 		copy_map_value_locked(map, old_val, value, false);
3018 	else
3019 		copy_map_value(map, old_val, value);
3020 
3021 	/*
3022 	 * Torn reads: a concurrent reader without BPF_F_LOCK may observe
3023 	 * the value mid-copy. Callers requiring consistent reads must use
3024 	 * BPF_F_LOCK, matching arraymap semantics.
3025 	 *
3026 	 * copy_map_value() skips special-field offsets, so old timers/
3027 	 * kptrs/etc. still sit in the slot. Cancel them after the copy
3028 	 * to match arraymap's update semantics.
3029 	 */
3030 	rhtab_check_and_free_fields(rhtab, elem);
3031 	return 0;
3032 }
3033 
3034 static long rhtab_map_update_elem(struct bpf_map *map, void *key, void *value, u64 map_flags)
3035 {
3036 	struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map);
3037 	struct rhtab_elem *elem, *tmp;
3038 
3039 	if (unlikely((map_flags & ~BPF_F_LOCK) > BPF_EXIST))
3040 		return -EINVAL;
3041 
3042 	if ((map_flags & BPF_F_LOCK) && !btf_record_has_field(map->record, BPF_SPIN_LOCK))
3043 		return -EINVAL;
3044 
3045 	guard(rcu)();
3046 	elem = rhtab_lookup_elem(map, key);
3047 	if (elem)
3048 		return rhtab_map_update_existing(map, elem, value, map_flags);
3049 
3050 	if (map_flags & BPF_EXIST)
3051 		return -ENOENT;
3052 
3053 	/*
3054 	 * Reject new insertions while map_release_uref cleanup walks the
3055 	 * table. Without this, new elements could keep triggering rehash
3056 	 * and prevent the walk from terminating.
3057 	 */
3058 	if (READ_ONCE(rhtab->freeing_internal))
3059 		return -EBUSY;
3060 
3061 	/* Check max_entries limit before inserting new element */
3062 	if (atomic_read(&rhtab->ht.nelems) >= map->max_entries)
3063 		return -E2BIG;
3064 
3065 	elem = bpf_mem_cache_alloc(&rhtab->ma);
3066 	if (!elem)
3067 		return -ENOMEM;
3068 
3069 	memcpy(elem->data, key, map->key_size);
3070 	copy_map_value(map, rhtab_elem_value(elem, map->key_size), value);
3071 	check_and_init_map_value(map, rhtab_elem_value(elem, map->key_size));
3072 
3073 	/* Prevent deadlock for NMI programs attempting to take bucket lock */
3074 	bpf_disable_instrumentation();
3075 
3076 	if (map->key_size == sizeof(long))
3077 		tmp = rhashtable_lookup_get_insert_fast(&rhtab->ht, &elem->node, rhtab_params_long);
3078 	else
3079 		tmp = rhashtable_lookup_get_insert_fast(&rhtab->ht, &elem->node, rhtab_params);
3080 
3081 	bpf_enable_instrumentation();
3082 
3083 	if (tmp) {
3084 		bpf_mem_cache_free(&rhtab->ma, elem);
3085 		if (IS_ERR(tmp))
3086 			return PTR_ERR(tmp);
3087 
3088 		return rhtab_map_update_existing(map, tmp, value, map_flags);
3089 	}
3090 
3091 	return 0;
3092 }
3093 
3094 static int rhtab_map_gen_lookup(struct bpf_map *map, struct bpf_insn *insn_buf)
3095 {
3096 	struct bpf_insn *insn = insn_buf;
3097 	const int ret = BPF_REG_0;
3098 
3099 	BUILD_BUG_ON(!__same_type(&rhtab_lookup_elem,
3100 				  (void *(*)(struct bpf_map *map, void *key)) NULL));
3101 	*insn++ = BPF_EMIT_CALL(rhtab_lookup_elem);
3102 	*insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 1);
3103 	*insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
3104 				offsetof(struct rhtab_elem, data) + round_up(map->key_size, 8));
3105 
3106 	return insn - insn_buf;
3107 }
3108 
3109 static int rhtab_map_check_btf(struct bpf_map *map, const struct btf *btf,
3110 			       const struct btf_type *key_type,
3111 			       const struct btf_type *value_type)
3112 {
3113 	struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map);
3114 
3115 	return bpf_ma_set_dtor(map, &rhtab->ma, rhtab_mem_dtor);
3116 }
3117 
3118 static void rhtab_map_free_internal_structs(struct bpf_map *map)
3119 {
3120 	struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map);
3121 	struct rhashtable_iter iter;
3122 	struct rhtab_elem *elem;
3123 
3124 	if (!bpf_map_has_internal_structs(map))
3125 		return;
3126 
3127 	/*
3128 	 * Block new insertions. Once observed, no new growth is triggered,
3129 	 * so any in-flight rehash will drain and the walker is guaranteed
3130 	 * to stop returning -EAGAIN. Treat -EAGAIN as "rehash in progress,
3131 	 * retry"; do not wait for the worker.
3132 	 */
3133 	WRITE_ONCE(rhtab->freeing_internal, true);
3134 
3135 	rhashtable_walk_enter(&rhtab->ht, &iter);
3136 	rhashtable_walk_start(&iter);
3137 
3138 	while ((elem = rhashtable_walk_next(&iter))) {
3139 		if (IS_ERR(elem)) {
3140 			if (PTR_ERR(elem) == -EAGAIN)
3141 				continue;
3142 			break;
3143 		}
3144 
3145 		bpf_map_free_internal_structs(map, rhtab_elem_value(elem, map->key_size));
3146 
3147 		if (need_resched()) { /* Avoid stalls on large maps */
3148 			rhashtable_walk_stop(&iter);
3149 			cond_resched();
3150 			rhashtable_walk_start(&iter);
3151 		}
3152 	}
3153 
3154 	rhashtable_walk_stop(&iter);
3155 	rhashtable_walk_exit(&iter);
3156 	WRITE_ONCE(rhtab->freeing_internal, false);
3157 }
3158 
3159 static int rhtab_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
3160 	__must_hold_shared(RCU)
3161 {
3162 	struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map);
3163 	struct rhtab_elem *elem;
3164 
3165 	elem = rhashtable_next_key(&rhtab->ht, key);
3166 
3167 	/* if not found, return the first key */
3168 	if (PTR_ERR(elem) == -ENOENT)
3169 		elem = rhashtable_next_key(&rhtab->ht, NULL);
3170 
3171 	if (IS_ERR(elem))
3172 		return PTR_ERR(elem);
3173 	if (!elem)
3174 		return -ENOENT;
3175 
3176 	memcpy(next_key, elem->data, map->key_size);
3177 	return 0;
3178 }
3179 
3180 static void rhtab_map_seq_show_elem(struct bpf_map *map, void *key, struct seq_file *m)
3181 {
3182 	void *value;
3183 
3184 	/* Guarantee that hashtab value is not freed */
3185 	guard(rcu)();
3186 
3187 	value = rhtab_map_lookup_elem(map, key);
3188 	if (!value)
3189 		return;
3190 
3191 	btf_type_seq_show(map->btf, map->btf_key_type_id, key, m);
3192 	seq_puts(m, ": ");
3193 	btf_type_seq_show(map->btf, map->btf_value_type_id, value, m);
3194 	seq_putc(m, '\n');
3195 }
3196 
3197 static long bpf_each_rhash_elem(struct bpf_map *map, bpf_callback_t callback_fn,
3198 				void *callback_ctx, u64 flags)
3199 {
3200 	struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map);
3201 	void *prev_key = NULL;
3202 	struct rhtab_elem *elem;
3203 	int num_elems = 0;
3204 	u64 ret = 0;
3205 
3206 	cant_migrate();
3207 
3208 	if (flags != 0)
3209 		return -EINVAL;
3210 
3211 	rcu_read_lock();
3212 	/*
3213 	 * Best-effort iteration: if rhashtable is concurrently resized or
3214 	 * elements are deleted/inserted, there may be missed or duplicate
3215 	 * elements visited.
3216 	 */
3217 	while ((elem = rhashtable_next_key(&rhtab->ht, prev_key))) {
3218 		if (IS_ERR(elem))
3219 			break;
3220 		num_elems++;
3221 		ret = callback_fn((u64)(long)map,
3222 				  (u64)(long)elem->data,
3223 				  (u64)(long)rhtab_elem_value(elem, map->key_size),
3224 				  (u64)(long)callback_ctx, 0);
3225 		if (ret)
3226 			break;
3227 
3228 		prev_key = elem->data;	/* valid while RCU held */
3229 	}
3230 	rcu_read_unlock();
3231 
3232 	return num_elems;
3233 }
3234 
3235 static u64 rhtab_map_mem_usage(const struct bpf_map *map)
3236 {
3237 	struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map);
3238 	u64 num_entries;
3239 
3240 	/* Excludes rhashtable bucket overhead (~ nelems * sizeof(void *) at 75% load). */
3241 	num_entries = atomic_read(&rhtab->ht.nelems);
3242 	return sizeof(struct bpf_rhtab) + rhtab->elem_size * num_entries;
3243 }
3244 
3245 static int __rhtab_map_lookup_and_delete_batch(struct bpf_map *map,
3246 					       const union bpf_attr *attr,
3247 					       union bpf_attr __user *uattr,
3248 					       bool do_delete)
3249 {
3250 	struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map);
3251 	void __user *uvalues = u64_to_user_ptr(attr->batch.values);
3252 	void __user *ukeys = u64_to_user_ptr(attr->batch.keys);
3253 	void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
3254 	void *cursor = NULL, *keys = NULL, *values = NULL, *dst_key, *dst_val;
3255 	struct rhtab_elem **del_elems = NULL;
3256 	u32 max_count, total, key_size, value_size, i;
3257 	bool has_next_cursor = false;
3258 	struct rhtab_elem *elem;
3259 	u64 elem_map_flags, map_flags;
3260 	int ret = 0;
3261 
3262 	elem_map_flags = attr->batch.elem_flags;
3263 	ret = bpf_map_check_op_flags(map, elem_map_flags, BPF_F_LOCK);
3264 	if (ret)
3265 		return ret;
3266 
3267 	map_flags = attr->batch.flags;
3268 	if (map_flags)
3269 		return -EINVAL;
3270 
3271 	max_count = attr->batch.count;
3272 	if (!max_count)
3273 		return 0;
3274 
3275 	if (put_user(0, &uattr->batch.count))
3276 		return -EFAULT;
3277 
3278 	key_size = map->key_size;
3279 	value_size = map->value_size;
3280 
3281 	keys = kvmalloc_array(max_count, key_size, GFP_USER | __GFP_NOWARN);
3282 	values = kvmalloc_array(max_count, value_size, GFP_USER | __GFP_NOWARN);
3283 	if (do_delete)
3284 		del_elems = kvmalloc_array(max_count, sizeof(void *),
3285 					   GFP_USER | __GFP_NOWARN);
3286 	cursor = kmalloc(key_size, GFP_USER | __GFP_NOWARN);
3287 
3288 	if (!keys || !values || !cursor || (do_delete && !del_elems)) {
3289 		ret = -ENOMEM;
3290 		goto free;
3291 	}
3292 
3293 	if (ubatch && copy_from_user(cursor, ubatch, key_size)) {
3294 		ret = -EFAULT;
3295 		goto free;
3296 	}
3297 
3298 	dst_key = keys;
3299 	dst_val = values;
3300 	total = 0;
3301 
3302 	rcu_read_lock();
3303 
3304 	/*
3305 	 * Cursor stores the key of the next-to-process element (stashed by
3306 	 * the previous batch). Look it up directly so the element is included
3307 	 * here rather than skipped by next_key(). If the cursor was deleted
3308 	 * concurrently (or by the previous do_delete batch), return -EAGAIN
3309 	 * so userspace can distinguish a lost cursor from end-of-iteration
3310 	 * (-ENOENT) and restart from a NULL cursor.
3311 	 */
3312 	if (ubatch) {
3313 		elem = rhtab_lookup_elem(map, cursor);
3314 		if (!elem) {
3315 			rcu_read_unlock();
3316 			ret = -EAGAIN;
3317 			goto free;
3318 		}
3319 	} else {
3320 		elem = rhashtable_next_key(&rhtab->ht, NULL);
3321 	}
3322 
3323 	while (elem && !IS_ERR(elem) && total < max_count) {
3324 		memcpy(dst_key, elem->data, key_size);
3325 		rhtab_read_elem_value(map, dst_val, elem, elem_map_flags);
3326 		check_and_init_map_value(map, dst_val);
3327 
3328 		if (do_delete)
3329 			del_elems[total] = elem;
3330 
3331 		elem = rhashtable_next_key(&rhtab->ht, dst_key);
3332 		dst_key += key_size;
3333 		dst_val += value_size;
3334 		total++;
3335 
3336 		/* Bail to userspace to avoid stalls. */
3337 		if (need_resched())
3338 			break;
3339 	}
3340 
3341 	if (elem && !IS_ERR(elem)) {
3342 		/* Stash next-to-process key as cursor for the next batch. */
3343 		memcpy(cursor, elem->data, key_size);
3344 		has_next_cursor = true;
3345 	}
3346 
3347 	if (do_delete) {
3348 		for (i = 0; i < total; i++)
3349 			rhtab_delete_elem(rhtab, del_elems[i], NULL, 0);
3350 	}
3351 
3352 	rcu_read_unlock();
3353 
3354 	if (total == 0) {
3355 		ret = -ENOENT;
3356 		goto free;
3357 	}
3358 
3359 	/* No more elements after this batch. */
3360 	if (!has_next_cursor)
3361 		ret = -ENOENT;
3362 
3363 	if (copy_to_user(ukeys, keys, (size_t)total * key_size) ||
3364 	    copy_to_user(uvalues, values, (size_t)total * value_size) ||
3365 	    put_user(total, &uattr->batch.count) ||
3366 	    (has_next_cursor &&
3367 	     copy_to_user(u64_to_user_ptr(attr->batch.out_batch),
3368 			  cursor, key_size))) {
3369 		ret = -EFAULT;
3370 		goto free;
3371 	}
3372 
3373 free:
3374 	kfree(cursor);
3375 	kvfree(keys);
3376 	kvfree(values);
3377 	kvfree(del_elems);
3378 	return ret;
3379 }
3380 
3381 static int rhtab_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
3382 				  union bpf_attr __user *uattr)
3383 {
3384 	return __rhtab_map_lookup_and_delete_batch(map, attr, uattr, false);
3385 }
3386 
3387 static int rhtab_map_lookup_and_delete_batch(struct bpf_map *map, const union bpf_attr *attr,
3388 					     union bpf_attr __user *uattr)
3389 {
3390 	return __rhtab_map_lookup_and_delete_batch(map, attr, uattr, true);
3391 }
3392 
3393 struct bpf_iter_seq_rhash_map_info {
3394 	struct bpf_map *map;
3395 	struct bpf_rhtab *rhtab;
3396 	struct rhashtable_iter iter;
3397 };
3398 
3399 static void *bpf_rhash_map_seq_start(struct seq_file *seq, loff_t *pos)
3400 	__acquires(RCU)
3401 {
3402 	struct bpf_iter_seq_rhash_map_info *info = seq->private;
3403 	struct rhtab_elem *elem;
3404 
3405 	rhashtable_walk_start(&info->iter);
3406 	/*
3407 	 * Re-deliver the element returned by walk_next() at the end of the
3408 	 * previous read() — bpf_seq_read may have stopped before show()
3409 	 * consumed it. Rehash rewinds the walker; retry on -EAGAIN.
3410 	 */
3411 	do {
3412 		elem = rhashtable_walk_peek(&info->iter);
3413 	} while (PTR_ERR(elem) == -EAGAIN);
3414 
3415 	if (IS_ERR(elem))
3416 		return NULL;
3417 
3418 	if (elem && *pos == 0)
3419 		++*pos;
3420 	return elem;
3421 }
3422 
3423 static void *bpf_rhash_map_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3424 {
3425 	struct bpf_iter_seq_rhash_map_info *info = seq->private;
3426 	struct rhtab_elem *elem;
3427 
3428 	++*pos;
3429 
3430 	/* Rehash rewinds the walker; retry until it stops returning -EAGAIN. */
3431 	do {
3432 		elem = rhashtable_walk_next(&info->iter);
3433 	} while (PTR_ERR(elem) == -EAGAIN);
3434 
3435 	if (IS_ERR(elem))
3436 		return NULL;
3437 	return elem;
3438 }
3439 
3440 static int __bpf_rhash_map_seq_show(struct seq_file *seq,
3441 				    struct rhtab_elem *elem)
3442 {
3443 	struct bpf_iter_seq_rhash_map_info *info = seq->private;
3444 	struct bpf_iter__bpf_map_elem ctx = {};
3445 	struct bpf_iter_meta meta;
3446 	struct bpf_prog *prog;
3447 	int ret = 0;
3448 
3449 	meta.seq = seq;
3450 	prog = bpf_iter_get_info(&meta, elem == NULL);
3451 	if (prog) {
3452 		ctx.meta = &meta;
3453 		ctx.map = info->map;
3454 		if (elem) {
3455 			ctx.key = elem->data;
3456 			ctx.value = rhtab_elem_value(elem, info->map->key_size);
3457 		}
3458 		ret = bpf_iter_run_prog(prog, &ctx);
3459 	}
3460 
3461 	return ret;
3462 }
3463 
3464 static int bpf_rhash_map_seq_show(struct seq_file *seq, void *v)
3465 {
3466 	return __bpf_rhash_map_seq_show(seq, v);
3467 }
3468 
3469 static void bpf_rhash_map_seq_stop(struct seq_file *seq, void *v)
3470 	__releases(RCU)
3471 {
3472 	struct bpf_iter_seq_rhash_map_info *info = seq->private;
3473 
3474 	if (!v)
3475 		(void)__bpf_rhash_map_seq_show(seq, NULL);
3476 
3477 	rhashtable_walk_stop(&info->iter);
3478 }
3479 
3480 static int bpf_iter_init_rhash_map(void *priv_data, struct bpf_iter_aux_info *aux)
3481 {
3482 	struct bpf_iter_seq_rhash_map_info *info = priv_data;
3483 	struct bpf_map *map = aux->map;
3484 
3485 	bpf_map_inc_with_uref(map);
3486 	info->map = map;
3487 	info->rhtab = container_of(map, struct bpf_rhtab, map);
3488 	rhashtable_walk_enter(&info->rhtab->ht, &info->iter);
3489 	return 0;
3490 }
3491 
3492 static void bpf_iter_fini_rhash_map(void *priv_data)
3493 {
3494 	struct bpf_iter_seq_rhash_map_info *info = priv_data;
3495 
3496 	rhashtable_walk_exit(&info->iter);
3497 	bpf_map_put_with_uref(info->map);
3498 }
3499 
3500 static const struct seq_operations bpf_rhash_map_seq_ops = {
3501 	.start = bpf_rhash_map_seq_start,
3502 	.next = bpf_rhash_map_seq_next,
3503 	.stop = bpf_rhash_map_seq_stop,
3504 	.show = bpf_rhash_map_seq_show,
3505 };
3506 
3507 static const struct bpf_iter_seq_info rhash_iter_seq_info = {
3508 	.seq_ops = &bpf_rhash_map_seq_ops,
3509 	.init_seq_private = bpf_iter_init_rhash_map,
3510 	.fini_seq_private = bpf_iter_fini_rhash_map,
3511 	.seq_priv_size = sizeof(struct bpf_iter_seq_rhash_map_info),
3512 };
3513 
3514 BTF_ID_LIST_SINGLE(rhtab_map_btf_ids, struct, bpf_rhtab)
3515 const struct bpf_map_ops rhtab_map_ops = {
3516 	.map_meta_equal = bpf_map_meta_equal,
3517 	.map_alloc_check = rhtab_map_alloc_check,
3518 	.map_alloc = rhtab_map_alloc,
3519 	.map_free = rhtab_map_free,
3520 	.map_get_next_key = rhtab_map_get_next_key,
3521 	.map_release_uref = rhtab_map_free_internal_structs,
3522 	.map_check_btf = rhtab_map_check_btf,
3523 	.map_lookup_elem = rhtab_map_lookup_elem,
3524 	.map_lookup_and_delete_elem = rhtab_map_lookup_and_delete_elem,
3525 	.map_update_elem = rhtab_map_update_elem,
3526 	.map_delete_elem = rhtab_map_delete_elem,
3527 	.map_gen_lookup = rhtab_map_gen_lookup,
3528 	.map_seq_show_elem = rhtab_map_seq_show_elem,
3529 	.map_set_for_each_callback_args = map_set_for_each_callback_args,
3530 	.map_for_each_callback = bpf_each_rhash_elem,
3531 	.map_mem_usage = rhtab_map_mem_usage,
3532 	BATCH_OPS(rhtab),
3533 	.map_btf_id = &rhtab_map_btf_ids[0],
3534 	.iter_seq_info = &rhash_iter_seq_info,
3535 };
3536