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