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