xref: /linux/kernel/bpf/hashtab.c (revision 1ae497c78f01855f3695b58481311ffdd429b028)
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 <uapi/linux/btf.h>
13 #include <linux/rcupdate_trace.h>
14 #include <linux/btf_ids.h>
15 #include "percpu_freelist.h"
16 #include "bpf_lru_list.h"
17 #include "map_in_map.h"
18 #include <linux/bpf_mem_alloc.h>
19 
20 #define HTAB_CREATE_FLAG_MASK						\
21 	(BPF_F_NO_PREALLOC | BPF_F_NO_COMMON_LRU | BPF_F_NUMA_NODE |	\
22 	 BPF_F_ACCESS_MASK | BPF_F_ZERO_SEED)
23 
24 #define BATCH_OPS(_name)			\
25 	.map_lookup_batch =			\
26 	_name##_map_lookup_batch,		\
27 	.map_lookup_and_delete_batch =		\
28 	_name##_map_lookup_and_delete_batch,	\
29 	.map_update_batch =			\
30 	generic_map_update_batch,		\
31 	.map_delete_batch =			\
32 	generic_map_delete_batch
33 
34 /*
35  * The bucket lock has two protection scopes:
36  *
37  * 1) Serializing concurrent operations from BPF programs on different
38  *    CPUs
39  *
40  * 2) Serializing concurrent operations from BPF programs and sys_bpf()
41  *
42  * BPF programs can execute in any context including perf, kprobes and
43  * tracing. As there are almost no limits where perf, kprobes and tracing
44  * can be invoked from the lock operations need to be protected against
45  * deadlocks. Deadlocks can be caused by recursion and by an invocation in
46  * the lock held section when functions which acquire this lock are invoked
47  * from sys_bpf(). BPF recursion is prevented by incrementing the per CPU
48  * variable bpf_prog_active, which prevents BPF programs attached to perf
49  * events, kprobes and tracing to be invoked before the prior invocation
50  * from one of these contexts completed. sys_bpf() uses the same mechanism
51  * by pinning the task to the current CPU and incrementing the recursion
52  * protection across the map operation.
53  *
54  * This has subtle implications on PREEMPT_RT. PREEMPT_RT forbids certain
55  * operations like memory allocations (even with GFP_ATOMIC) from atomic
56  * contexts. This is required because even with GFP_ATOMIC the memory
57  * allocator calls into code paths which acquire locks with long held lock
58  * sections. To ensure the deterministic behaviour these locks are regular
59  * spinlocks, which are converted to 'sleepable' spinlocks on RT. The only
60  * true atomic contexts on an RT kernel are the low level hardware
61  * handling, scheduling, low level interrupt handling, NMIs etc. None of
62  * these contexts should ever do memory allocations.
63  *
64  * As regular device interrupt handlers and soft interrupts are forced into
65  * thread context, the existing code which does
66  *   spin_lock*(); alloc(GFP_ATOMIC); spin_unlock*();
67  * just works.
68  *
69  * In theory the BPF locks could be converted to regular spinlocks as well,
70  * but the bucket locks and percpu_freelist locks can be taken from
71  * arbitrary contexts (perf, kprobes, tracepoints) which are required to be
72  * atomic contexts even on RT. Before the introduction of bpf_mem_alloc,
73  * it is only safe to use raw spinlock for preallocated hash map on a RT kernel,
74  * because there is no memory allocation within the lock held sections. However
75  * after hash map was fully converted to use bpf_mem_alloc, there will be
76  * non-synchronous memory allocation for non-preallocated hash map, so it is
77  * safe to always use raw spinlock for bucket lock.
78  */
79 struct bucket {
80 	struct hlist_nulls_head head;
81 	raw_spinlock_t raw_lock;
82 };
83 
84 #define HASHTAB_MAP_LOCK_COUNT 8
85 #define HASHTAB_MAP_LOCK_MASK (HASHTAB_MAP_LOCK_COUNT - 1)
86 
87 struct bpf_htab {
88 	struct bpf_map map;
89 	struct bpf_mem_alloc ma;
90 	struct bpf_mem_alloc pcpu_ma;
91 	struct bucket *buckets;
92 	void *elems;
93 	union {
94 		struct pcpu_freelist freelist;
95 		struct bpf_lru lru;
96 	};
97 	struct htab_elem *__percpu *extra_elems;
98 	/* number of elements in non-preallocated hashtable are kept
99 	 * in either pcount or count
100 	 */
101 	struct percpu_counter pcount;
102 	atomic_t count;
103 	bool use_percpu_counter;
104 	u32 n_buckets;	/* number of hash buckets */
105 	u32 elem_size;	/* size of each element in bytes */
106 	u32 hashrnd;
107 	struct lock_class_key lockdep_key;
108 	int __percpu *map_locked[HASHTAB_MAP_LOCK_COUNT];
109 };
110 
111 /* each htab element is struct htab_elem + key + value */
112 struct htab_elem {
113 	union {
114 		struct hlist_nulls_node hash_node;
115 		struct {
116 			void *padding;
117 			union {
118 				struct pcpu_freelist_node fnode;
119 				struct htab_elem *batch_flink;
120 			};
121 		};
122 	};
123 	union {
124 		/* pointer to per-cpu pointer */
125 		void *ptr_to_pptr;
126 		struct bpf_lru_node lru_node;
127 	};
128 	u32 hash;
129 	char key[] __aligned(8);
130 };
131 
132 static inline bool htab_is_prealloc(const struct bpf_htab *htab)
133 {
134 	return !(htab->map.map_flags & BPF_F_NO_PREALLOC);
135 }
136 
137 static void htab_init_buckets(struct bpf_htab *htab)
138 {
139 	unsigned int i;
140 
141 	for (i = 0; i < htab->n_buckets; i++) {
142 		INIT_HLIST_NULLS_HEAD(&htab->buckets[i].head, i);
143 		raw_spin_lock_init(&htab->buckets[i].raw_lock);
144 		lockdep_set_class(&htab->buckets[i].raw_lock,
145 					  &htab->lockdep_key);
146 		cond_resched();
147 	}
148 }
149 
150 static inline int htab_lock_bucket(const struct bpf_htab *htab,
151 				   struct bucket *b, u32 hash,
152 				   unsigned long *pflags)
153 {
154 	unsigned long flags;
155 
156 	hash = hash & min_t(u32, HASHTAB_MAP_LOCK_MASK, htab->n_buckets - 1);
157 
158 	preempt_disable();
159 	local_irq_save(flags);
160 	if (unlikely(__this_cpu_inc_return(*(htab->map_locked[hash])) != 1)) {
161 		__this_cpu_dec(*(htab->map_locked[hash]));
162 		local_irq_restore(flags);
163 		preempt_enable();
164 		return -EBUSY;
165 	}
166 
167 	raw_spin_lock(&b->raw_lock);
168 	*pflags = flags;
169 
170 	return 0;
171 }
172 
173 static inline void htab_unlock_bucket(const struct bpf_htab *htab,
174 				      struct bucket *b, u32 hash,
175 				      unsigned long flags)
176 {
177 	hash = hash & min_t(u32, HASHTAB_MAP_LOCK_MASK, htab->n_buckets - 1);
178 	raw_spin_unlock(&b->raw_lock);
179 	__this_cpu_dec(*(htab->map_locked[hash]));
180 	local_irq_restore(flags);
181 	preempt_enable();
182 }
183 
184 static bool htab_lru_map_delete_node(void *arg, struct bpf_lru_node *node);
185 
186 static bool htab_is_lru(const struct bpf_htab *htab)
187 {
188 	return htab->map.map_type == BPF_MAP_TYPE_LRU_HASH ||
189 		htab->map.map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH;
190 }
191 
192 static bool htab_is_percpu(const struct bpf_htab *htab)
193 {
194 	return htab->map.map_type == BPF_MAP_TYPE_PERCPU_HASH ||
195 		htab->map.map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH;
196 }
197 
198 static inline void htab_elem_set_ptr(struct htab_elem *l, u32 key_size,
199 				     void __percpu *pptr)
200 {
201 	*(void __percpu **)(l->key + key_size) = pptr;
202 }
203 
204 static inline void __percpu *htab_elem_get_ptr(struct htab_elem *l, u32 key_size)
205 {
206 	return *(void __percpu **)(l->key + key_size);
207 }
208 
209 static void *fd_htab_map_get_ptr(const struct bpf_map *map, struct htab_elem *l)
210 {
211 	return *(void **)(l->key + roundup(map->key_size, 8));
212 }
213 
214 static struct htab_elem *get_htab_elem(struct bpf_htab *htab, int i)
215 {
216 	return (struct htab_elem *) (htab->elems + i * (u64)htab->elem_size);
217 }
218 
219 static bool htab_has_extra_elems(struct bpf_htab *htab)
220 {
221 	return !htab_is_percpu(htab) && !htab_is_lru(htab);
222 }
223 
224 static void htab_free_prealloced_timers_and_wq(struct bpf_htab *htab)
225 {
226 	u32 num_entries = htab->map.max_entries;
227 	int i;
228 
229 	if (htab_has_extra_elems(htab))
230 		num_entries += num_possible_cpus();
231 
232 	for (i = 0; i < num_entries; i++) {
233 		struct htab_elem *elem;
234 
235 		elem = get_htab_elem(htab, i);
236 		if (btf_record_has_field(htab->map.record, BPF_TIMER))
237 			bpf_obj_free_timer(htab->map.record,
238 					   elem->key + round_up(htab->map.key_size, 8));
239 		if (btf_record_has_field(htab->map.record, BPF_WORKQUEUE))
240 			bpf_obj_free_workqueue(htab->map.record,
241 					       elem->key + round_up(htab->map.key_size, 8));
242 		cond_resched();
243 	}
244 }
245 
246 static void htab_free_prealloced_fields(struct bpf_htab *htab)
247 {
248 	u32 num_entries = htab->map.max_entries;
249 	int i;
250 
251 	if (IS_ERR_OR_NULL(htab->map.record))
252 		return;
253 	if (htab_has_extra_elems(htab))
254 		num_entries += num_possible_cpus();
255 	for (i = 0; i < num_entries; i++) {
256 		struct htab_elem *elem;
257 
258 		elem = get_htab_elem(htab, i);
259 		if (htab_is_percpu(htab)) {
260 			void __percpu *pptr = htab_elem_get_ptr(elem, htab->map.key_size);
261 			int cpu;
262 
263 			for_each_possible_cpu(cpu) {
264 				bpf_obj_free_fields(htab->map.record, per_cpu_ptr(pptr, cpu));
265 				cond_resched();
266 			}
267 		} else {
268 			bpf_obj_free_fields(htab->map.record, elem->key + round_up(htab->map.key_size, 8));
269 			cond_resched();
270 		}
271 		cond_resched();
272 	}
273 }
274 
275 static void htab_free_elems(struct bpf_htab *htab)
276 {
277 	int i;
278 
279 	if (!htab_is_percpu(htab))
280 		goto free_elems;
281 
282 	for (i = 0; i < htab->map.max_entries; i++) {
283 		void __percpu *pptr;
284 
285 		pptr = htab_elem_get_ptr(get_htab_elem(htab, i),
286 					 htab->map.key_size);
287 		free_percpu(pptr);
288 		cond_resched();
289 	}
290 free_elems:
291 	bpf_map_area_free(htab->elems);
292 }
293 
294 /* The LRU list has a lock (lru_lock). Each htab bucket has a lock
295  * (bucket_lock). If both locks need to be acquired together, the lock
296  * order is always lru_lock -> bucket_lock and this only happens in
297  * bpf_lru_list.c logic. For example, certain code path of
298  * bpf_lru_pop_free(), which is called by function prealloc_lru_pop(),
299  * will acquire lru_lock first followed by acquiring bucket_lock.
300  *
301  * In hashtab.c, to avoid deadlock, lock acquisition of
302  * bucket_lock followed by lru_lock is not allowed. In such cases,
303  * bucket_lock needs to be released first before acquiring lru_lock.
304  */
305 static struct htab_elem *prealloc_lru_pop(struct bpf_htab *htab, void *key,
306 					  u32 hash)
307 {
308 	struct bpf_lru_node *node = bpf_lru_pop_free(&htab->lru, hash);
309 	struct htab_elem *l;
310 
311 	if (node) {
312 		bpf_map_inc_elem_count(&htab->map);
313 		l = container_of(node, struct htab_elem, lru_node);
314 		memcpy(l->key, key, htab->map.key_size);
315 		return l;
316 	}
317 
318 	return NULL;
319 }
320 
321 static int prealloc_init(struct bpf_htab *htab)
322 {
323 	u32 num_entries = htab->map.max_entries;
324 	int err = -ENOMEM, i;
325 
326 	if (htab_has_extra_elems(htab))
327 		num_entries += num_possible_cpus();
328 
329 	htab->elems = bpf_map_area_alloc((u64)htab->elem_size * num_entries,
330 					 htab->map.numa_node);
331 	if (!htab->elems)
332 		return -ENOMEM;
333 
334 	if (!htab_is_percpu(htab))
335 		goto skip_percpu_elems;
336 
337 	for (i = 0; i < num_entries; i++) {
338 		u32 size = round_up(htab->map.value_size, 8);
339 		void __percpu *pptr;
340 
341 		pptr = bpf_map_alloc_percpu(&htab->map, size, 8,
342 					    GFP_USER | __GFP_NOWARN);
343 		if (!pptr)
344 			goto free_elems;
345 		htab_elem_set_ptr(get_htab_elem(htab, i), htab->map.key_size,
346 				  pptr);
347 		cond_resched();
348 	}
349 
350 skip_percpu_elems:
351 	if (htab_is_lru(htab))
352 		err = bpf_lru_init(&htab->lru,
353 				   htab->map.map_flags & BPF_F_NO_COMMON_LRU,
354 				   offsetof(struct htab_elem, hash) -
355 				   offsetof(struct htab_elem, lru_node),
356 				   htab_lru_map_delete_node,
357 				   htab);
358 	else
359 		err = pcpu_freelist_init(&htab->freelist);
360 
361 	if (err)
362 		goto free_elems;
363 
364 	if (htab_is_lru(htab))
365 		bpf_lru_populate(&htab->lru, htab->elems,
366 				 offsetof(struct htab_elem, lru_node),
367 				 htab->elem_size, num_entries);
368 	else
369 		pcpu_freelist_populate(&htab->freelist,
370 				       htab->elems + offsetof(struct htab_elem, fnode),
371 				       htab->elem_size, num_entries);
372 
373 	return 0;
374 
375 free_elems:
376 	htab_free_elems(htab);
377 	return err;
378 }
379 
380 static void prealloc_destroy(struct bpf_htab *htab)
381 {
382 	htab_free_elems(htab);
383 
384 	if (htab_is_lru(htab))
385 		bpf_lru_destroy(&htab->lru);
386 	else
387 		pcpu_freelist_destroy(&htab->freelist);
388 }
389 
390 static int alloc_extra_elems(struct bpf_htab *htab)
391 {
392 	struct htab_elem *__percpu *pptr, *l_new;
393 	struct pcpu_freelist_node *l;
394 	int cpu;
395 
396 	pptr = bpf_map_alloc_percpu(&htab->map, sizeof(struct htab_elem *), 8,
397 				    GFP_USER | __GFP_NOWARN);
398 	if (!pptr)
399 		return -ENOMEM;
400 
401 	for_each_possible_cpu(cpu) {
402 		l = pcpu_freelist_pop(&htab->freelist);
403 		/* pop will succeed, since prealloc_init()
404 		 * preallocated extra num_possible_cpus elements
405 		 */
406 		l_new = container_of(l, struct htab_elem, fnode);
407 		*per_cpu_ptr(pptr, cpu) = l_new;
408 	}
409 	htab->extra_elems = pptr;
410 	return 0;
411 }
412 
413 /* Called from syscall */
414 static int htab_map_alloc_check(union bpf_attr *attr)
415 {
416 	bool percpu = (attr->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
417 		       attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);
418 	bool lru = (attr->map_type == BPF_MAP_TYPE_LRU_HASH ||
419 		    attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);
420 	/* percpu_lru means each cpu has its own LRU list.
421 	 * it is different from BPF_MAP_TYPE_PERCPU_HASH where
422 	 * the map's value itself is percpu.  percpu_lru has
423 	 * nothing to do with the map's value.
424 	 */
425 	bool percpu_lru = (attr->map_flags & BPF_F_NO_COMMON_LRU);
426 	bool prealloc = !(attr->map_flags & BPF_F_NO_PREALLOC);
427 	bool zero_seed = (attr->map_flags & BPF_F_ZERO_SEED);
428 	int numa_node = bpf_map_attr_numa_node(attr);
429 
430 	BUILD_BUG_ON(offsetof(struct htab_elem, fnode.next) !=
431 		     offsetof(struct htab_elem, hash_node.pprev));
432 
433 	if (zero_seed && !capable(CAP_SYS_ADMIN))
434 		/* Guard against local DoS, and discourage production use. */
435 		return -EPERM;
436 
437 	if (attr->map_flags & ~HTAB_CREATE_FLAG_MASK ||
438 	    !bpf_map_flags_access_ok(attr->map_flags))
439 		return -EINVAL;
440 
441 	if (!lru && percpu_lru)
442 		return -EINVAL;
443 
444 	if (lru && !prealloc)
445 		return -ENOTSUPP;
446 
447 	if (numa_node != NUMA_NO_NODE && (percpu || percpu_lru))
448 		return -EINVAL;
449 
450 	/* check sanity of attributes.
451 	 * value_size == 0 may be allowed in the future to use map as a set
452 	 */
453 	if (attr->max_entries == 0 || attr->key_size == 0 ||
454 	    attr->value_size == 0)
455 		return -EINVAL;
456 
457 	if ((u64)attr->key_size + attr->value_size >= KMALLOC_MAX_SIZE -
458 	   sizeof(struct htab_elem))
459 		/* if key_size + value_size is bigger, the user space won't be
460 		 * able to access the elements via bpf syscall. This check
461 		 * also makes sure that the elem_size doesn't overflow and it's
462 		 * kmalloc-able later in htab_map_update_elem()
463 		 */
464 		return -E2BIG;
465 
466 	return 0;
467 }
468 
469 static struct bpf_map *htab_map_alloc(union bpf_attr *attr)
470 {
471 	bool percpu = (attr->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
472 		       attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);
473 	bool lru = (attr->map_type == BPF_MAP_TYPE_LRU_HASH ||
474 		    attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);
475 	/* percpu_lru means each cpu has its own LRU list.
476 	 * it is different from BPF_MAP_TYPE_PERCPU_HASH where
477 	 * the map's value itself is percpu.  percpu_lru has
478 	 * nothing to do with the map's value.
479 	 */
480 	bool percpu_lru = (attr->map_flags & BPF_F_NO_COMMON_LRU);
481 	bool prealloc = !(attr->map_flags & BPF_F_NO_PREALLOC);
482 	struct bpf_htab *htab;
483 	int err, i;
484 
485 	htab = bpf_map_area_alloc(sizeof(*htab), NUMA_NO_NODE);
486 	if (!htab)
487 		return ERR_PTR(-ENOMEM);
488 
489 	lockdep_register_key(&htab->lockdep_key);
490 
491 	bpf_map_init_from_attr(&htab->map, attr);
492 
493 	if (percpu_lru) {
494 		/* ensure each CPU's lru list has >=1 elements.
495 		 * since we are at it, make each lru list has the same
496 		 * number of elements.
497 		 */
498 		htab->map.max_entries = roundup(attr->max_entries,
499 						num_possible_cpus());
500 		if (htab->map.max_entries < attr->max_entries)
501 			htab->map.max_entries = rounddown(attr->max_entries,
502 							  num_possible_cpus());
503 	}
504 
505 	/* hash table size must be power of 2; roundup_pow_of_two() can overflow
506 	 * into UB on 32-bit arches, so check that first
507 	 */
508 	err = -E2BIG;
509 	if (htab->map.max_entries > 1UL << 31)
510 		goto free_htab;
511 
512 	htab->n_buckets = roundup_pow_of_two(htab->map.max_entries);
513 
514 	htab->elem_size = sizeof(struct htab_elem) +
515 			  round_up(htab->map.key_size, 8);
516 	if (percpu)
517 		htab->elem_size += sizeof(void *);
518 	else
519 		htab->elem_size += round_up(htab->map.value_size, 8);
520 
521 	/* check for u32 overflow */
522 	if (htab->n_buckets > U32_MAX / sizeof(struct bucket))
523 		goto free_htab;
524 
525 	err = bpf_map_init_elem_count(&htab->map);
526 	if (err)
527 		goto free_htab;
528 
529 	err = -ENOMEM;
530 	htab->buckets = bpf_map_area_alloc(htab->n_buckets *
531 					   sizeof(struct bucket),
532 					   htab->map.numa_node);
533 	if (!htab->buckets)
534 		goto free_elem_count;
535 
536 	for (i = 0; i < HASHTAB_MAP_LOCK_COUNT; i++) {
537 		htab->map_locked[i] = bpf_map_alloc_percpu(&htab->map,
538 							   sizeof(int),
539 							   sizeof(int),
540 							   GFP_USER);
541 		if (!htab->map_locked[i])
542 			goto free_map_locked;
543 	}
544 
545 	if (htab->map.map_flags & BPF_F_ZERO_SEED)
546 		htab->hashrnd = 0;
547 	else
548 		htab->hashrnd = get_random_u32();
549 
550 	htab_init_buckets(htab);
551 
552 /* compute_batch_value() computes batch value as num_online_cpus() * 2
553  * and __percpu_counter_compare() needs
554  * htab->max_entries - cur_number_of_elems to be more than batch * num_online_cpus()
555  * for percpu_counter to be faster than atomic_t. In practice the average bpf
556  * hash map size is 10k, which means that a system with 64 cpus will fill
557  * hashmap to 20% of 10k before percpu_counter becomes ineffective. Therefore
558  * define our own batch count as 32 then 10k hash map can be filled up to 80%:
559  * 10k - 8k > 32 _batch_ * 64 _cpus_
560  * and __percpu_counter_compare() will still be fast. At that point hash map
561  * collisions will dominate its performance anyway. Assume that hash map filled
562  * to 50+% isn't going to be O(1) and use the following formula to choose
563  * between percpu_counter and atomic_t.
564  */
565 #define PERCPU_COUNTER_BATCH 32
566 	if (attr->max_entries / 2 > num_online_cpus() * PERCPU_COUNTER_BATCH)
567 		htab->use_percpu_counter = true;
568 
569 	if (htab->use_percpu_counter) {
570 		err = percpu_counter_init(&htab->pcount, 0, GFP_KERNEL);
571 		if (err)
572 			goto free_map_locked;
573 	}
574 
575 	if (prealloc) {
576 		err = prealloc_init(htab);
577 		if (err)
578 			goto free_map_locked;
579 
580 		if (!percpu && !lru) {
581 			/* lru itself can remove the least used element, so
582 			 * there is no need for an extra elem during map_update.
583 			 */
584 			err = alloc_extra_elems(htab);
585 			if (err)
586 				goto free_prealloc;
587 		}
588 	} else {
589 		err = bpf_mem_alloc_init(&htab->ma, htab->elem_size, false);
590 		if (err)
591 			goto free_map_locked;
592 		if (percpu) {
593 			err = bpf_mem_alloc_init(&htab->pcpu_ma,
594 						 round_up(htab->map.value_size, 8), true);
595 			if (err)
596 				goto free_map_locked;
597 		}
598 	}
599 
600 	return &htab->map;
601 
602 free_prealloc:
603 	prealloc_destroy(htab);
604 free_map_locked:
605 	if (htab->use_percpu_counter)
606 		percpu_counter_destroy(&htab->pcount);
607 	for (i = 0; i < HASHTAB_MAP_LOCK_COUNT; i++)
608 		free_percpu(htab->map_locked[i]);
609 	bpf_map_area_free(htab->buckets);
610 	bpf_mem_alloc_destroy(&htab->pcpu_ma);
611 	bpf_mem_alloc_destroy(&htab->ma);
612 free_elem_count:
613 	bpf_map_free_elem_count(&htab->map);
614 free_htab:
615 	lockdep_unregister_key(&htab->lockdep_key);
616 	bpf_map_area_free(htab);
617 	return ERR_PTR(err);
618 }
619 
620 static inline u32 htab_map_hash(const void *key, u32 key_len, u32 hashrnd)
621 {
622 	if (likely(key_len % 4 == 0))
623 		return jhash2(key, key_len / 4, hashrnd);
624 	return jhash(key, key_len, hashrnd);
625 }
626 
627 static inline struct bucket *__select_bucket(struct bpf_htab *htab, u32 hash)
628 {
629 	return &htab->buckets[hash & (htab->n_buckets - 1)];
630 }
631 
632 static inline struct hlist_nulls_head *select_bucket(struct bpf_htab *htab, u32 hash)
633 {
634 	return &__select_bucket(htab, hash)->head;
635 }
636 
637 /* this lookup function can only be called with bucket lock taken */
638 static struct htab_elem *lookup_elem_raw(struct hlist_nulls_head *head, u32 hash,
639 					 void *key, u32 key_size)
640 {
641 	struct hlist_nulls_node *n;
642 	struct htab_elem *l;
643 
644 	hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
645 		if (l->hash == hash && !memcmp(&l->key, key, key_size))
646 			return l;
647 
648 	return NULL;
649 }
650 
651 /* can be called without bucket lock. it will repeat the loop in
652  * the unlikely event when elements moved from one bucket into another
653  * while link list is being walked
654  */
655 static struct htab_elem *lookup_nulls_elem_raw(struct hlist_nulls_head *head,
656 					       u32 hash, void *key,
657 					       u32 key_size, u32 n_buckets)
658 {
659 	struct hlist_nulls_node *n;
660 	struct htab_elem *l;
661 
662 again:
663 	hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
664 		if (l->hash == hash && !memcmp(&l->key, key, key_size))
665 			return l;
666 
667 	if (unlikely(get_nulls_value(n) != (hash & (n_buckets - 1))))
668 		goto again;
669 
670 	return NULL;
671 }
672 
673 /* Called from syscall or from eBPF program directly, so
674  * arguments have to match bpf_map_lookup_elem() exactly.
675  * The return value is adjusted by BPF instructions
676  * in htab_map_gen_lookup().
677  */
678 static void *__htab_map_lookup_elem(struct bpf_map *map, void *key)
679 {
680 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
681 	struct hlist_nulls_head *head;
682 	struct htab_elem *l;
683 	u32 hash, key_size;
684 
685 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
686 		     !rcu_read_lock_bh_held());
687 
688 	key_size = map->key_size;
689 
690 	hash = htab_map_hash(key, key_size, htab->hashrnd);
691 
692 	head = select_bucket(htab, hash);
693 
694 	l = lookup_nulls_elem_raw(head, hash, key, key_size, htab->n_buckets);
695 
696 	return l;
697 }
698 
699 static void *htab_map_lookup_elem(struct bpf_map *map, void *key)
700 {
701 	struct htab_elem *l = __htab_map_lookup_elem(map, key);
702 
703 	if (l)
704 		return l->key + round_up(map->key_size, 8);
705 
706 	return NULL;
707 }
708 
709 /* inline bpf_map_lookup_elem() call.
710  * Instead of:
711  * bpf_prog
712  *   bpf_map_lookup_elem
713  *     map->ops->map_lookup_elem
714  *       htab_map_lookup_elem
715  *         __htab_map_lookup_elem
716  * do:
717  * bpf_prog
718  *   __htab_map_lookup_elem
719  */
720 static int htab_map_gen_lookup(struct bpf_map *map, struct bpf_insn *insn_buf)
721 {
722 	struct bpf_insn *insn = insn_buf;
723 	const int ret = BPF_REG_0;
724 
725 	BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
726 		     (void *(*)(struct bpf_map *map, void *key))NULL));
727 	*insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
728 	*insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 1);
729 	*insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
730 				offsetof(struct htab_elem, key) +
731 				round_up(map->key_size, 8));
732 	return insn - insn_buf;
733 }
734 
735 static __always_inline void *__htab_lru_map_lookup_elem(struct bpf_map *map,
736 							void *key, const bool mark)
737 {
738 	struct htab_elem *l = __htab_map_lookup_elem(map, key);
739 
740 	if (l) {
741 		if (mark)
742 			bpf_lru_node_set_ref(&l->lru_node);
743 		return l->key + round_up(map->key_size, 8);
744 	}
745 
746 	return NULL;
747 }
748 
749 static void *htab_lru_map_lookup_elem(struct bpf_map *map, void *key)
750 {
751 	return __htab_lru_map_lookup_elem(map, key, true);
752 }
753 
754 static void *htab_lru_map_lookup_elem_sys(struct bpf_map *map, void *key)
755 {
756 	return __htab_lru_map_lookup_elem(map, key, false);
757 }
758 
759 static int htab_lru_map_gen_lookup(struct bpf_map *map,
760 				   struct bpf_insn *insn_buf)
761 {
762 	struct bpf_insn *insn = insn_buf;
763 	const int ret = BPF_REG_0;
764 	const int ref_reg = BPF_REG_1;
765 
766 	BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
767 		     (void *(*)(struct bpf_map *map, void *key))NULL));
768 	*insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
769 	*insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 4);
770 	*insn++ = BPF_LDX_MEM(BPF_B, ref_reg, ret,
771 			      offsetof(struct htab_elem, lru_node) +
772 			      offsetof(struct bpf_lru_node, ref));
773 	*insn++ = BPF_JMP_IMM(BPF_JNE, ref_reg, 0, 1);
774 	*insn++ = BPF_ST_MEM(BPF_B, ret,
775 			     offsetof(struct htab_elem, lru_node) +
776 			     offsetof(struct bpf_lru_node, ref),
777 			     1);
778 	*insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
779 				offsetof(struct htab_elem, key) +
780 				round_up(map->key_size, 8));
781 	return insn - insn_buf;
782 }
783 
784 static void check_and_free_fields(struct bpf_htab *htab,
785 				  struct htab_elem *elem)
786 {
787 	if (htab_is_percpu(htab)) {
788 		void __percpu *pptr = htab_elem_get_ptr(elem, htab->map.key_size);
789 		int cpu;
790 
791 		for_each_possible_cpu(cpu)
792 			bpf_obj_free_fields(htab->map.record, per_cpu_ptr(pptr, cpu));
793 	} else {
794 		void *map_value = elem->key + round_up(htab->map.key_size, 8);
795 
796 		bpf_obj_free_fields(htab->map.record, map_value);
797 	}
798 }
799 
800 /* It is called from the bpf_lru_list when the LRU needs to delete
801  * older elements from the htab.
802  */
803 static bool htab_lru_map_delete_node(void *arg, struct bpf_lru_node *node)
804 {
805 	struct bpf_htab *htab = arg;
806 	struct htab_elem *l = NULL, *tgt_l;
807 	struct hlist_nulls_head *head;
808 	struct hlist_nulls_node *n;
809 	unsigned long flags;
810 	struct bucket *b;
811 	int ret;
812 
813 	tgt_l = container_of(node, struct htab_elem, lru_node);
814 	b = __select_bucket(htab, tgt_l->hash);
815 	head = &b->head;
816 
817 	ret = htab_lock_bucket(htab, b, tgt_l->hash, &flags);
818 	if (ret)
819 		return false;
820 
821 	hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
822 		if (l == tgt_l) {
823 			hlist_nulls_del_rcu(&l->hash_node);
824 			check_and_free_fields(htab, l);
825 			bpf_map_dec_elem_count(&htab->map);
826 			break;
827 		}
828 
829 	htab_unlock_bucket(htab, b, tgt_l->hash, flags);
830 
831 	return l == tgt_l;
832 }
833 
834 /* Called from syscall */
835 static int htab_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
836 {
837 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
838 	struct hlist_nulls_head *head;
839 	struct htab_elem *l, *next_l;
840 	u32 hash, key_size;
841 	int i = 0;
842 
843 	WARN_ON_ONCE(!rcu_read_lock_held());
844 
845 	key_size = map->key_size;
846 
847 	if (!key)
848 		goto find_first_elem;
849 
850 	hash = htab_map_hash(key, key_size, htab->hashrnd);
851 
852 	head = select_bucket(htab, hash);
853 
854 	/* lookup the key */
855 	l = lookup_nulls_elem_raw(head, hash, key, key_size, htab->n_buckets);
856 
857 	if (!l)
858 		goto find_first_elem;
859 
860 	/* key was found, get next key in the same bucket */
861 	next_l = hlist_nulls_entry_safe(rcu_dereference_raw(hlist_nulls_next_rcu(&l->hash_node)),
862 				  struct htab_elem, hash_node);
863 
864 	if (next_l) {
865 		/* if next elem in this hash list is non-zero, just return it */
866 		memcpy(next_key, next_l->key, key_size);
867 		return 0;
868 	}
869 
870 	/* no more elements in this hash list, go to the next bucket */
871 	i = hash & (htab->n_buckets - 1);
872 	i++;
873 
874 find_first_elem:
875 	/* iterate over buckets */
876 	for (; i < htab->n_buckets; i++) {
877 		head = select_bucket(htab, i);
878 
879 		/* pick first element in the bucket */
880 		next_l = hlist_nulls_entry_safe(rcu_dereference_raw(hlist_nulls_first_rcu(head)),
881 					  struct htab_elem, hash_node);
882 		if (next_l) {
883 			/* if it's not empty, just return it */
884 			memcpy(next_key, next_l->key, key_size);
885 			return 0;
886 		}
887 	}
888 
889 	/* iterated over all buckets and all elements */
890 	return -ENOENT;
891 }
892 
893 static void htab_elem_free(struct bpf_htab *htab, struct htab_elem *l)
894 {
895 	check_and_free_fields(htab, l);
896 	if (htab->map.map_type == BPF_MAP_TYPE_PERCPU_HASH)
897 		bpf_mem_cache_free(&htab->pcpu_ma, l->ptr_to_pptr);
898 	bpf_mem_cache_free(&htab->ma, l);
899 }
900 
901 static void htab_put_fd_value(struct bpf_htab *htab, struct htab_elem *l)
902 {
903 	struct bpf_map *map = &htab->map;
904 	void *ptr;
905 
906 	if (map->ops->map_fd_put_ptr) {
907 		ptr = fd_htab_map_get_ptr(map, l);
908 		map->ops->map_fd_put_ptr(map, ptr, true);
909 	}
910 }
911 
912 static bool is_map_full(struct bpf_htab *htab)
913 {
914 	if (htab->use_percpu_counter)
915 		return __percpu_counter_compare(&htab->pcount, htab->map.max_entries,
916 						PERCPU_COUNTER_BATCH) >= 0;
917 	return atomic_read(&htab->count) >= htab->map.max_entries;
918 }
919 
920 static void inc_elem_count(struct bpf_htab *htab)
921 {
922 	bpf_map_inc_elem_count(&htab->map);
923 
924 	if (htab->use_percpu_counter)
925 		percpu_counter_add_batch(&htab->pcount, 1, PERCPU_COUNTER_BATCH);
926 	else
927 		atomic_inc(&htab->count);
928 }
929 
930 static void dec_elem_count(struct bpf_htab *htab)
931 {
932 	bpf_map_dec_elem_count(&htab->map);
933 
934 	if (htab->use_percpu_counter)
935 		percpu_counter_add_batch(&htab->pcount, -1, PERCPU_COUNTER_BATCH);
936 	else
937 		atomic_dec(&htab->count);
938 }
939 
940 
941 static void free_htab_elem(struct bpf_htab *htab, struct htab_elem *l)
942 {
943 	htab_put_fd_value(htab, l);
944 
945 	if (htab_is_prealloc(htab)) {
946 		bpf_map_dec_elem_count(&htab->map);
947 		check_and_free_fields(htab, l);
948 		__pcpu_freelist_push(&htab->freelist, &l->fnode);
949 	} else {
950 		dec_elem_count(htab);
951 		htab_elem_free(htab, l);
952 	}
953 }
954 
955 static void pcpu_copy_value(struct bpf_htab *htab, void __percpu *pptr,
956 			    void *value, bool onallcpus)
957 {
958 	if (!onallcpus) {
959 		/* copy true value_size bytes */
960 		copy_map_value(&htab->map, this_cpu_ptr(pptr), value);
961 	} else {
962 		u32 size = round_up(htab->map.value_size, 8);
963 		int off = 0, cpu;
964 
965 		for_each_possible_cpu(cpu) {
966 			copy_map_value_long(&htab->map, per_cpu_ptr(pptr, cpu), value + off);
967 			off += size;
968 		}
969 	}
970 }
971 
972 static void pcpu_init_value(struct bpf_htab *htab, void __percpu *pptr,
973 			    void *value, bool onallcpus)
974 {
975 	/* When not setting the initial value on all cpus, zero-fill element
976 	 * values for other cpus. Otherwise, bpf program has no way to ensure
977 	 * known initial values for cpus other than current one
978 	 * (onallcpus=false always when coming from bpf prog).
979 	 */
980 	if (!onallcpus) {
981 		int current_cpu = raw_smp_processor_id();
982 		int cpu;
983 
984 		for_each_possible_cpu(cpu) {
985 			if (cpu == current_cpu)
986 				copy_map_value_long(&htab->map, per_cpu_ptr(pptr, cpu), value);
987 			else /* Since elem is preallocated, we cannot touch special fields */
988 				zero_map_value(&htab->map, per_cpu_ptr(pptr, cpu));
989 		}
990 	} else {
991 		pcpu_copy_value(htab, pptr, value, onallcpus);
992 	}
993 }
994 
995 static bool fd_htab_map_needs_adjust(const struct bpf_htab *htab)
996 {
997 	return htab->map.map_type == BPF_MAP_TYPE_HASH_OF_MAPS &&
998 	       BITS_PER_LONG == 64;
999 }
1000 
1001 static struct htab_elem *alloc_htab_elem(struct bpf_htab *htab, void *key,
1002 					 void *value, u32 key_size, u32 hash,
1003 					 bool percpu, bool onallcpus,
1004 					 struct htab_elem *old_elem)
1005 {
1006 	u32 size = htab->map.value_size;
1007 	bool prealloc = htab_is_prealloc(htab);
1008 	struct htab_elem *l_new, **pl_new;
1009 	void __percpu *pptr;
1010 
1011 	if (prealloc) {
1012 		if (old_elem) {
1013 			/* if we're updating the existing element,
1014 			 * use per-cpu extra elems to avoid freelist_pop/push
1015 			 */
1016 			pl_new = this_cpu_ptr(htab->extra_elems);
1017 			l_new = *pl_new;
1018 			htab_put_fd_value(htab, old_elem);
1019 			*pl_new = old_elem;
1020 		} else {
1021 			struct pcpu_freelist_node *l;
1022 
1023 			l = __pcpu_freelist_pop(&htab->freelist);
1024 			if (!l)
1025 				return ERR_PTR(-E2BIG);
1026 			l_new = container_of(l, struct htab_elem, fnode);
1027 			bpf_map_inc_elem_count(&htab->map);
1028 		}
1029 	} else {
1030 		if (is_map_full(htab))
1031 			if (!old_elem)
1032 				/* when map is full and update() is replacing
1033 				 * old element, it's ok to allocate, since
1034 				 * old element will be freed immediately.
1035 				 * Otherwise return an error
1036 				 */
1037 				return ERR_PTR(-E2BIG);
1038 		inc_elem_count(htab);
1039 		l_new = bpf_mem_cache_alloc(&htab->ma);
1040 		if (!l_new) {
1041 			l_new = ERR_PTR(-ENOMEM);
1042 			goto dec_count;
1043 		}
1044 	}
1045 
1046 	memcpy(l_new->key, key, key_size);
1047 	if (percpu) {
1048 		if (prealloc) {
1049 			pptr = htab_elem_get_ptr(l_new, key_size);
1050 		} else {
1051 			/* alloc_percpu zero-fills */
1052 			void *ptr = bpf_mem_cache_alloc(&htab->pcpu_ma);
1053 
1054 			if (!ptr) {
1055 				bpf_mem_cache_free(&htab->ma, l_new);
1056 				l_new = ERR_PTR(-ENOMEM);
1057 				goto dec_count;
1058 			}
1059 			l_new->ptr_to_pptr = ptr;
1060 			pptr = *(void __percpu **)ptr;
1061 		}
1062 
1063 		pcpu_init_value(htab, pptr, value, onallcpus);
1064 
1065 		if (!prealloc)
1066 			htab_elem_set_ptr(l_new, key_size, pptr);
1067 	} else if (fd_htab_map_needs_adjust(htab)) {
1068 		size = round_up(size, 8);
1069 		memcpy(l_new->key + round_up(key_size, 8), value, size);
1070 	} else {
1071 		copy_map_value(&htab->map,
1072 			       l_new->key + round_up(key_size, 8),
1073 			       value);
1074 	}
1075 
1076 	l_new->hash = hash;
1077 	return l_new;
1078 dec_count:
1079 	dec_elem_count(htab);
1080 	return l_new;
1081 }
1082 
1083 static int check_flags(struct bpf_htab *htab, struct htab_elem *l_old,
1084 		       u64 map_flags)
1085 {
1086 	if (l_old && (map_flags & ~BPF_F_LOCK) == BPF_NOEXIST)
1087 		/* elem already exists */
1088 		return -EEXIST;
1089 
1090 	if (!l_old && (map_flags & ~BPF_F_LOCK) == BPF_EXIST)
1091 		/* elem doesn't exist, cannot update it */
1092 		return -ENOENT;
1093 
1094 	return 0;
1095 }
1096 
1097 /* Called from syscall or from eBPF program */
1098 static long htab_map_update_elem(struct bpf_map *map, void *key, void *value,
1099 				 u64 map_flags)
1100 {
1101 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1102 	struct htab_elem *l_new = NULL, *l_old;
1103 	struct hlist_nulls_head *head;
1104 	unsigned long flags;
1105 	struct bucket *b;
1106 	u32 key_size, hash;
1107 	int ret;
1108 
1109 	if (unlikely((map_flags & ~BPF_F_LOCK) > BPF_EXIST))
1110 		/* unknown flags */
1111 		return -EINVAL;
1112 
1113 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1114 		     !rcu_read_lock_bh_held());
1115 
1116 	key_size = map->key_size;
1117 
1118 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1119 
1120 	b = __select_bucket(htab, hash);
1121 	head = &b->head;
1122 
1123 	if (unlikely(map_flags & BPF_F_LOCK)) {
1124 		if (unlikely(!btf_record_has_field(map->record, BPF_SPIN_LOCK)))
1125 			return -EINVAL;
1126 		/* find an element without taking the bucket lock */
1127 		l_old = lookup_nulls_elem_raw(head, hash, key, key_size,
1128 					      htab->n_buckets);
1129 		ret = check_flags(htab, l_old, map_flags);
1130 		if (ret)
1131 			return ret;
1132 		if (l_old) {
1133 			/* grab the element lock and update value in place */
1134 			copy_map_value_locked(map,
1135 					      l_old->key + round_up(key_size, 8),
1136 					      value, false);
1137 			return 0;
1138 		}
1139 		/* fall through, grab the bucket lock and lookup again.
1140 		 * 99.9% chance that the element won't be found,
1141 		 * but second lookup under lock has to be done.
1142 		 */
1143 	}
1144 
1145 	ret = htab_lock_bucket(htab, b, hash, &flags);
1146 	if (ret)
1147 		return ret;
1148 
1149 	l_old = lookup_elem_raw(head, hash, key, key_size);
1150 
1151 	ret = check_flags(htab, l_old, map_flags);
1152 	if (ret)
1153 		goto err;
1154 
1155 	if (unlikely(l_old && (map_flags & BPF_F_LOCK))) {
1156 		/* first lookup without the bucket lock didn't find the element,
1157 		 * but second lookup with the bucket lock found it.
1158 		 * This case is highly unlikely, but has to be dealt with:
1159 		 * grab the element lock in addition to the bucket lock
1160 		 * and update element in place
1161 		 */
1162 		copy_map_value_locked(map,
1163 				      l_old->key + round_up(key_size, 8),
1164 				      value, false);
1165 		ret = 0;
1166 		goto err;
1167 	}
1168 
1169 	l_new = alloc_htab_elem(htab, key, value, key_size, hash, false, false,
1170 				l_old);
1171 	if (IS_ERR(l_new)) {
1172 		/* all pre-allocated elements are in use or memory exhausted */
1173 		ret = PTR_ERR(l_new);
1174 		goto err;
1175 	}
1176 
1177 	/* add new element to the head of the list, so that
1178 	 * concurrent search will find it before old elem
1179 	 */
1180 	hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1181 	if (l_old) {
1182 		hlist_nulls_del_rcu(&l_old->hash_node);
1183 		if (!htab_is_prealloc(htab))
1184 			free_htab_elem(htab, l_old);
1185 		else
1186 			check_and_free_fields(htab, l_old);
1187 	}
1188 	ret = 0;
1189 err:
1190 	htab_unlock_bucket(htab, b, hash, flags);
1191 	return ret;
1192 }
1193 
1194 static void htab_lru_push_free(struct bpf_htab *htab, struct htab_elem *elem)
1195 {
1196 	check_and_free_fields(htab, elem);
1197 	bpf_map_dec_elem_count(&htab->map);
1198 	bpf_lru_push_free(&htab->lru, &elem->lru_node);
1199 }
1200 
1201 static long htab_lru_map_update_elem(struct bpf_map *map, void *key, void *value,
1202 				     u64 map_flags)
1203 {
1204 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1205 	struct htab_elem *l_new, *l_old = NULL;
1206 	struct hlist_nulls_head *head;
1207 	unsigned long flags;
1208 	struct bucket *b;
1209 	u32 key_size, hash;
1210 	int ret;
1211 
1212 	if (unlikely(map_flags > BPF_EXIST))
1213 		/* unknown flags */
1214 		return -EINVAL;
1215 
1216 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1217 		     !rcu_read_lock_bh_held());
1218 
1219 	key_size = map->key_size;
1220 
1221 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1222 
1223 	b = __select_bucket(htab, hash);
1224 	head = &b->head;
1225 
1226 	/* For LRU, we need to alloc before taking bucket's
1227 	 * spinlock because getting free nodes from LRU may need
1228 	 * to remove older elements from htab and this removal
1229 	 * operation will need a bucket lock.
1230 	 */
1231 	l_new = prealloc_lru_pop(htab, key, hash);
1232 	if (!l_new)
1233 		return -ENOMEM;
1234 	copy_map_value(&htab->map,
1235 		       l_new->key + round_up(map->key_size, 8), value);
1236 
1237 	ret = htab_lock_bucket(htab, b, hash, &flags);
1238 	if (ret)
1239 		goto err_lock_bucket;
1240 
1241 	l_old = lookup_elem_raw(head, hash, key, key_size);
1242 
1243 	ret = check_flags(htab, l_old, map_flags);
1244 	if (ret)
1245 		goto err;
1246 
1247 	/* add new element to the head of the list, so that
1248 	 * concurrent search will find it before old elem
1249 	 */
1250 	hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1251 	if (l_old) {
1252 		bpf_lru_node_set_ref(&l_new->lru_node);
1253 		hlist_nulls_del_rcu(&l_old->hash_node);
1254 	}
1255 	ret = 0;
1256 
1257 err:
1258 	htab_unlock_bucket(htab, b, hash, flags);
1259 
1260 err_lock_bucket:
1261 	if (ret)
1262 		htab_lru_push_free(htab, l_new);
1263 	else if (l_old)
1264 		htab_lru_push_free(htab, l_old);
1265 
1266 	return ret;
1267 }
1268 
1269 static long __htab_percpu_map_update_elem(struct bpf_map *map, void *key,
1270 					  void *value, u64 map_flags,
1271 					  bool onallcpus)
1272 {
1273 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1274 	struct htab_elem *l_new = NULL, *l_old;
1275 	struct hlist_nulls_head *head;
1276 	unsigned long flags;
1277 	struct bucket *b;
1278 	u32 key_size, hash;
1279 	int ret;
1280 
1281 	if (unlikely(map_flags > BPF_EXIST))
1282 		/* unknown flags */
1283 		return -EINVAL;
1284 
1285 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1286 		     !rcu_read_lock_bh_held());
1287 
1288 	key_size = map->key_size;
1289 
1290 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1291 
1292 	b = __select_bucket(htab, hash);
1293 	head = &b->head;
1294 
1295 	ret = htab_lock_bucket(htab, b, hash, &flags);
1296 	if (ret)
1297 		return ret;
1298 
1299 	l_old = lookup_elem_raw(head, hash, key, key_size);
1300 
1301 	ret = check_flags(htab, l_old, map_flags);
1302 	if (ret)
1303 		goto err;
1304 
1305 	if (l_old) {
1306 		/* per-cpu hash map can update value in-place */
1307 		pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size),
1308 				value, onallcpus);
1309 	} else {
1310 		l_new = alloc_htab_elem(htab, key, value, key_size,
1311 					hash, true, onallcpus, NULL);
1312 		if (IS_ERR(l_new)) {
1313 			ret = PTR_ERR(l_new);
1314 			goto err;
1315 		}
1316 		hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1317 	}
1318 	ret = 0;
1319 err:
1320 	htab_unlock_bucket(htab, b, hash, flags);
1321 	return ret;
1322 }
1323 
1324 static long __htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key,
1325 					      void *value, u64 map_flags,
1326 					      bool onallcpus)
1327 {
1328 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1329 	struct htab_elem *l_new = NULL, *l_old;
1330 	struct hlist_nulls_head *head;
1331 	unsigned long flags;
1332 	struct bucket *b;
1333 	u32 key_size, hash;
1334 	int ret;
1335 
1336 	if (unlikely(map_flags > BPF_EXIST))
1337 		/* unknown flags */
1338 		return -EINVAL;
1339 
1340 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1341 		     !rcu_read_lock_bh_held());
1342 
1343 	key_size = map->key_size;
1344 
1345 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1346 
1347 	b = __select_bucket(htab, hash);
1348 	head = &b->head;
1349 
1350 	/* For LRU, we need to alloc before taking bucket's
1351 	 * spinlock because LRU's elem alloc may need
1352 	 * to remove older elem from htab and this removal
1353 	 * operation will need a bucket lock.
1354 	 */
1355 	if (map_flags != BPF_EXIST) {
1356 		l_new = prealloc_lru_pop(htab, key, hash);
1357 		if (!l_new)
1358 			return -ENOMEM;
1359 	}
1360 
1361 	ret = htab_lock_bucket(htab, b, hash, &flags);
1362 	if (ret)
1363 		goto err_lock_bucket;
1364 
1365 	l_old = lookup_elem_raw(head, hash, key, key_size);
1366 
1367 	ret = check_flags(htab, l_old, map_flags);
1368 	if (ret)
1369 		goto err;
1370 
1371 	if (l_old) {
1372 		bpf_lru_node_set_ref(&l_old->lru_node);
1373 
1374 		/* per-cpu hash map can update value in-place */
1375 		pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size),
1376 				value, onallcpus);
1377 	} else {
1378 		pcpu_init_value(htab, htab_elem_get_ptr(l_new, key_size),
1379 				value, onallcpus);
1380 		hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1381 		l_new = NULL;
1382 	}
1383 	ret = 0;
1384 err:
1385 	htab_unlock_bucket(htab, b, hash, flags);
1386 err_lock_bucket:
1387 	if (l_new) {
1388 		bpf_map_dec_elem_count(&htab->map);
1389 		bpf_lru_push_free(&htab->lru, &l_new->lru_node);
1390 	}
1391 	return ret;
1392 }
1393 
1394 static long htab_percpu_map_update_elem(struct bpf_map *map, void *key,
1395 					void *value, u64 map_flags)
1396 {
1397 	return __htab_percpu_map_update_elem(map, key, value, map_flags, false);
1398 }
1399 
1400 static long htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key,
1401 					    void *value, u64 map_flags)
1402 {
1403 	return __htab_lru_percpu_map_update_elem(map, key, value, map_flags,
1404 						 false);
1405 }
1406 
1407 /* Called from syscall or from eBPF program */
1408 static long htab_map_delete_elem(struct bpf_map *map, void *key)
1409 {
1410 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1411 	struct hlist_nulls_head *head;
1412 	struct bucket *b;
1413 	struct htab_elem *l;
1414 	unsigned long flags;
1415 	u32 hash, key_size;
1416 	int ret;
1417 
1418 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1419 		     !rcu_read_lock_bh_held());
1420 
1421 	key_size = map->key_size;
1422 
1423 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1424 	b = __select_bucket(htab, hash);
1425 	head = &b->head;
1426 
1427 	ret = htab_lock_bucket(htab, b, hash, &flags);
1428 	if (ret)
1429 		return ret;
1430 
1431 	l = lookup_elem_raw(head, hash, key, key_size);
1432 
1433 	if (l) {
1434 		hlist_nulls_del_rcu(&l->hash_node);
1435 		free_htab_elem(htab, l);
1436 	} else {
1437 		ret = -ENOENT;
1438 	}
1439 
1440 	htab_unlock_bucket(htab, b, hash, flags);
1441 	return ret;
1442 }
1443 
1444 static long htab_lru_map_delete_elem(struct bpf_map *map, void *key)
1445 {
1446 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1447 	struct hlist_nulls_head *head;
1448 	struct bucket *b;
1449 	struct htab_elem *l;
1450 	unsigned long flags;
1451 	u32 hash, key_size;
1452 	int ret;
1453 
1454 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1455 		     !rcu_read_lock_bh_held());
1456 
1457 	key_size = map->key_size;
1458 
1459 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1460 	b = __select_bucket(htab, hash);
1461 	head = &b->head;
1462 
1463 	ret = htab_lock_bucket(htab, b, hash, &flags);
1464 	if (ret)
1465 		return ret;
1466 
1467 	l = lookup_elem_raw(head, hash, key, key_size);
1468 
1469 	if (l)
1470 		hlist_nulls_del_rcu(&l->hash_node);
1471 	else
1472 		ret = -ENOENT;
1473 
1474 	htab_unlock_bucket(htab, b, hash, flags);
1475 	if (l)
1476 		htab_lru_push_free(htab, l);
1477 	return ret;
1478 }
1479 
1480 static void delete_all_elements(struct bpf_htab *htab)
1481 {
1482 	int i;
1483 
1484 	/* It's called from a worker thread, so disable migration here,
1485 	 * since bpf_mem_cache_free() relies on that.
1486 	 */
1487 	migrate_disable();
1488 	for (i = 0; i < htab->n_buckets; i++) {
1489 		struct hlist_nulls_head *head = select_bucket(htab, i);
1490 		struct hlist_nulls_node *n;
1491 		struct htab_elem *l;
1492 
1493 		hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
1494 			hlist_nulls_del_rcu(&l->hash_node);
1495 			htab_elem_free(htab, l);
1496 		}
1497 		cond_resched();
1498 	}
1499 	migrate_enable();
1500 }
1501 
1502 static void htab_free_malloced_timers_and_wq(struct bpf_htab *htab)
1503 {
1504 	int i;
1505 
1506 	rcu_read_lock();
1507 	for (i = 0; i < htab->n_buckets; i++) {
1508 		struct hlist_nulls_head *head = select_bucket(htab, i);
1509 		struct hlist_nulls_node *n;
1510 		struct htab_elem *l;
1511 
1512 		hlist_nulls_for_each_entry(l, n, head, hash_node) {
1513 			/* We only free timer on uref dropping to zero */
1514 			if (btf_record_has_field(htab->map.record, BPF_TIMER))
1515 				bpf_obj_free_timer(htab->map.record,
1516 						   l->key + round_up(htab->map.key_size, 8));
1517 			if (btf_record_has_field(htab->map.record, BPF_WORKQUEUE))
1518 				bpf_obj_free_workqueue(htab->map.record,
1519 						       l->key + round_up(htab->map.key_size, 8));
1520 		}
1521 		cond_resched_rcu();
1522 	}
1523 	rcu_read_unlock();
1524 }
1525 
1526 static void htab_map_free_timers_and_wq(struct bpf_map *map)
1527 {
1528 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1529 
1530 	/* We only free timer and workqueue on uref dropping to zero */
1531 	if (btf_record_has_field(htab->map.record, BPF_TIMER | BPF_WORKQUEUE)) {
1532 		if (!htab_is_prealloc(htab))
1533 			htab_free_malloced_timers_and_wq(htab);
1534 		else
1535 			htab_free_prealloced_timers_and_wq(htab);
1536 	}
1537 }
1538 
1539 /* Called when map->refcnt goes to zero, either from workqueue or from syscall */
1540 static void htab_map_free(struct bpf_map *map)
1541 {
1542 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1543 	int i;
1544 
1545 	/* bpf_free_used_maps() or close(map_fd) will trigger this map_free callback.
1546 	 * bpf_free_used_maps() is called after bpf prog is no longer executing.
1547 	 * There is no need to synchronize_rcu() here to protect map elements.
1548 	 */
1549 
1550 	/* htab no longer uses call_rcu() directly. bpf_mem_alloc does it
1551 	 * underneath and is responsible for waiting for callbacks to finish
1552 	 * during bpf_mem_alloc_destroy().
1553 	 */
1554 	if (!htab_is_prealloc(htab)) {
1555 		delete_all_elements(htab);
1556 	} else {
1557 		htab_free_prealloced_fields(htab);
1558 		prealloc_destroy(htab);
1559 	}
1560 
1561 	bpf_map_free_elem_count(map);
1562 	free_percpu(htab->extra_elems);
1563 	bpf_map_area_free(htab->buckets);
1564 	bpf_mem_alloc_destroy(&htab->pcpu_ma);
1565 	bpf_mem_alloc_destroy(&htab->ma);
1566 	if (htab->use_percpu_counter)
1567 		percpu_counter_destroy(&htab->pcount);
1568 	for (i = 0; i < HASHTAB_MAP_LOCK_COUNT; i++)
1569 		free_percpu(htab->map_locked[i]);
1570 	lockdep_unregister_key(&htab->lockdep_key);
1571 	bpf_map_area_free(htab);
1572 }
1573 
1574 static void htab_map_seq_show_elem(struct bpf_map *map, void *key,
1575 				   struct seq_file *m)
1576 {
1577 	void *value;
1578 
1579 	rcu_read_lock();
1580 
1581 	value = htab_map_lookup_elem(map, key);
1582 	if (!value) {
1583 		rcu_read_unlock();
1584 		return;
1585 	}
1586 
1587 	btf_type_seq_show(map->btf, map->btf_key_type_id, key, m);
1588 	seq_puts(m, ": ");
1589 	btf_type_seq_show(map->btf, map->btf_value_type_id, value, m);
1590 	seq_putc(m, '\n');
1591 
1592 	rcu_read_unlock();
1593 }
1594 
1595 static int __htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
1596 					     void *value, bool is_lru_map,
1597 					     bool is_percpu, u64 flags)
1598 {
1599 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1600 	struct hlist_nulls_head *head;
1601 	unsigned long bflags;
1602 	struct htab_elem *l;
1603 	u32 hash, key_size;
1604 	struct bucket *b;
1605 	int ret;
1606 
1607 	key_size = map->key_size;
1608 
1609 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1610 	b = __select_bucket(htab, hash);
1611 	head = &b->head;
1612 
1613 	ret = htab_lock_bucket(htab, b, hash, &bflags);
1614 	if (ret)
1615 		return ret;
1616 
1617 	l = lookup_elem_raw(head, hash, key, key_size);
1618 	if (!l) {
1619 		ret = -ENOENT;
1620 	} else {
1621 		if (is_percpu) {
1622 			u32 roundup_value_size = round_up(map->value_size, 8);
1623 			void __percpu *pptr;
1624 			int off = 0, cpu;
1625 
1626 			pptr = htab_elem_get_ptr(l, key_size);
1627 			for_each_possible_cpu(cpu) {
1628 				copy_map_value_long(&htab->map, value + off, per_cpu_ptr(pptr, cpu));
1629 				check_and_init_map_value(&htab->map, value + off);
1630 				off += roundup_value_size;
1631 			}
1632 		} else {
1633 			u32 roundup_key_size = round_up(map->key_size, 8);
1634 
1635 			if (flags & BPF_F_LOCK)
1636 				copy_map_value_locked(map, value, l->key +
1637 						      roundup_key_size,
1638 						      true);
1639 			else
1640 				copy_map_value(map, value, l->key +
1641 					       roundup_key_size);
1642 			/* Zeroing special fields in the temp buffer */
1643 			check_and_init_map_value(map, value);
1644 		}
1645 
1646 		hlist_nulls_del_rcu(&l->hash_node);
1647 		if (!is_lru_map)
1648 			free_htab_elem(htab, l);
1649 	}
1650 
1651 	htab_unlock_bucket(htab, b, hash, bflags);
1652 
1653 	if (is_lru_map && l)
1654 		htab_lru_push_free(htab, l);
1655 
1656 	return ret;
1657 }
1658 
1659 static int htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
1660 					   void *value, u64 flags)
1661 {
1662 	return __htab_map_lookup_and_delete_elem(map, key, value, false, false,
1663 						 flags);
1664 }
1665 
1666 static int htab_percpu_map_lookup_and_delete_elem(struct bpf_map *map,
1667 						  void *key, void *value,
1668 						  u64 flags)
1669 {
1670 	return __htab_map_lookup_and_delete_elem(map, key, value, false, true,
1671 						 flags);
1672 }
1673 
1674 static int htab_lru_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
1675 					       void *value, u64 flags)
1676 {
1677 	return __htab_map_lookup_and_delete_elem(map, key, value, true, false,
1678 						 flags);
1679 }
1680 
1681 static int htab_lru_percpu_map_lookup_and_delete_elem(struct bpf_map *map,
1682 						      void *key, void *value,
1683 						      u64 flags)
1684 {
1685 	return __htab_map_lookup_and_delete_elem(map, key, value, true, true,
1686 						 flags);
1687 }
1688 
1689 static int
1690 __htab_map_lookup_and_delete_batch(struct bpf_map *map,
1691 				   const union bpf_attr *attr,
1692 				   union bpf_attr __user *uattr,
1693 				   bool do_delete, bool is_lru_map,
1694 				   bool is_percpu)
1695 {
1696 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1697 	u32 bucket_cnt, total, key_size, value_size, roundup_key_size;
1698 	void *keys = NULL, *values = NULL, *value, *dst_key, *dst_val;
1699 	void __user *uvalues = u64_to_user_ptr(attr->batch.values);
1700 	void __user *ukeys = u64_to_user_ptr(attr->batch.keys);
1701 	void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1702 	u32 batch, max_count, size, bucket_size, map_id;
1703 	struct htab_elem *node_to_free = NULL;
1704 	u64 elem_map_flags, map_flags;
1705 	struct hlist_nulls_head *head;
1706 	struct hlist_nulls_node *n;
1707 	unsigned long flags = 0;
1708 	bool locked = false;
1709 	struct htab_elem *l;
1710 	struct bucket *b;
1711 	int ret = 0;
1712 
1713 	elem_map_flags = attr->batch.elem_flags;
1714 	if ((elem_map_flags & ~BPF_F_LOCK) ||
1715 	    ((elem_map_flags & BPF_F_LOCK) && !btf_record_has_field(map->record, BPF_SPIN_LOCK)))
1716 		return -EINVAL;
1717 
1718 	map_flags = attr->batch.flags;
1719 	if (map_flags)
1720 		return -EINVAL;
1721 
1722 	max_count = attr->batch.count;
1723 	if (!max_count)
1724 		return 0;
1725 
1726 	if (put_user(0, &uattr->batch.count))
1727 		return -EFAULT;
1728 
1729 	batch = 0;
1730 	if (ubatch && copy_from_user(&batch, ubatch, sizeof(batch)))
1731 		return -EFAULT;
1732 
1733 	if (batch >= htab->n_buckets)
1734 		return -ENOENT;
1735 
1736 	key_size = htab->map.key_size;
1737 	roundup_key_size = round_up(htab->map.key_size, 8);
1738 	value_size = htab->map.value_size;
1739 	size = round_up(value_size, 8);
1740 	if (is_percpu)
1741 		value_size = size * num_possible_cpus();
1742 	total = 0;
1743 	/* while experimenting with hash tables with sizes ranging from 10 to
1744 	 * 1000, it was observed that a bucket can have up to 5 entries.
1745 	 */
1746 	bucket_size = 5;
1747 
1748 alloc:
1749 	/* We cannot do copy_from_user or copy_to_user inside
1750 	 * the rcu_read_lock. Allocate enough space here.
1751 	 */
1752 	keys = kvmalloc_array(key_size, bucket_size, GFP_USER | __GFP_NOWARN);
1753 	values = kvmalloc_array(value_size, bucket_size, GFP_USER | __GFP_NOWARN);
1754 	if (!keys || !values) {
1755 		ret = -ENOMEM;
1756 		goto after_loop;
1757 	}
1758 
1759 again:
1760 	bpf_disable_instrumentation();
1761 	rcu_read_lock();
1762 again_nocopy:
1763 	dst_key = keys;
1764 	dst_val = values;
1765 	b = &htab->buckets[batch];
1766 	head = &b->head;
1767 	/* do not grab the lock unless need it (bucket_cnt > 0). */
1768 	if (locked) {
1769 		ret = htab_lock_bucket(htab, b, batch, &flags);
1770 		if (ret) {
1771 			rcu_read_unlock();
1772 			bpf_enable_instrumentation();
1773 			goto after_loop;
1774 		}
1775 	}
1776 
1777 	bucket_cnt = 0;
1778 	hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
1779 		bucket_cnt++;
1780 
1781 	if (bucket_cnt && !locked) {
1782 		locked = true;
1783 		goto again_nocopy;
1784 	}
1785 
1786 	if (bucket_cnt > (max_count - total)) {
1787 		if (total == 0)
1788 			ret = -ENOSPC;
1789 		/* Note that since bucket_cnt > 0 here, it is implicit
1790 		 * that the locked was grabbed, so release it.
1791 		 */
1792 		htab_unlock_bucket(htab, b, batch, flags);
1793 		rcu_read_unlock();
1794 		bpf_enable_instrumentation();
1795 		goto after_loop;
1796 	}
1797 
1798 	if (bucket_cnt > bucket_size) {
1799 		bucket_size = bucket_cnt;
1800 		/* Note that since bucket_cnt > 0 here, it is implicit
1801 		 * that the locked was grabbed, so release it.
1802 		 */
1803 		htab_unlock_bucket(htab, b, batch, flags);
1804 		rcu_read_unlock();
1805 		bpf_enable_instrumentation();
1806 		kvfree(keys);
1807 		kvfree(values);
1808 		goto alloc;
1809 	}
1810 
1811 	/* Next block is only safe to run if you have grabbed the lock */
1812 	if (!locked)
1813 		goto next_batch;
1814 
1815 	hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
1816 		memcpy(dst_key, l->key, key_size);
1817 
1818 		if (is_percpu) {
1819 			int off = 0, cpu;
1820 			void __percpu *pptr;
1821 
1822 			pptr = htab_elem_get_ptr(l, map->key_size);
1823 			for_each_possible_cpu(cpu) {
1824 				copy_map_value_long(&htab->map, dst_val + off, per_cpu_ptr(pptr, cpu));
1825 				check_and_init_map_value(&htab->map, dst_val + off);
1826 				off += size;
1827 			}
1828 		} else {
1829 			value = l->key + roundup_key_size;
1830 			if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
1831 				struct bpf_map **inner_map = value;
1832 
1833 				 /* Actual value is the id of the inner map */
1834 				map_id = map->ops->map_fd_sys_lookup_elem(*inner_map);
1835 				value = &map_id;
1836 			}
1837 
1838 			if (elem_map_flags & BPF_F_LOCK)
1839 				copy_map_value_locked(map, dst_val, value,
1840 						      true);
1841 			else
1842 				copy_map_value(map, dst_val, value);
1843 			/* Zeroing special fields in the temp buffer */
1844 			check_and_init_map_value(map, dst_val);
1845 		}
1846 		if (do_delete) {
1847 			hlist_nulls_del_rcu(&l->hash_node);
1848 
1849 			/* bpf_lru_push_free() will acquire lru_lock, which
1850 			 * may cause deadlock. See comments in function
1851 			 * prealloc_lru_pop(). Let us do bpf_lru_push_free()
1852 			 * after releasing the bucket lock.
1853 			 */
1854 			if (is_lru_map) {
1855 				l->batch_flink = node_to_free;
1856 				node_to_free = l;
1857 			} else {
1858 				free_htab_elem(htab, l);
1859 			}
1860 		}
1861 		dst_key += key_size;
1862 		dst_val += value_size;
1863 	}
1864 
1865 	htab_unlock_bucket(htab, b, batch, flags);
1866 	locked = false;
1867 
1868 	while (node_to_free) {
1869 		l = node_to_free;
1870 		node_to_free = node_to_free->batch_flink;
1871 		htab_lru_push_free(htab, l);
1872 	}
1873 
1874 next_batch:
1875 	/* If we are not copying data, we can go to next bucket and avoid
1876 	 * unlocking the rcu.
1877 	 */
1878 	if (!bucket_cnt && (batch + 1 < htab->n_buckets)) {
1879 		batch++;
1880 		goto again_nocopy;
1881 	}
1882 
1883 	rcu_read_unlock();
1884 	bpf_enable_instrumentation();
1885 	if (bucket_cnt && (copy_to_user(ukeys + total * key_size, keys,
1886 	    key_size * bucket_cnt) ||
1887 	    copy_to_user(uvalues + total * value_size, values,
1888 	    value_size * bucket_cnt))) {
1889 		ret = -EFAULT;
1890 		goto after_loop;
1891 	}
1892 
1893 	total += bucket_cnt;
1894 	batch++;
1895 	if (batch >= htab->n_buckets) {
1896 		ret = -ENOENT;
1897 		goto after_loop;
1898 	}
1899 	goto again;
1900 
1901 after_loop:
1902 	if (ret == -EFAULT)
1903 		goto out;
1904 
1905 	/* copy # of entries and next batch */
1906 	ubatch = u64_to_user_ptr(attr->batch.out_batch);
1907 	if (copy_to_user(ubatch, &batch, sizeof(batch)) ||
1908 	    put_user(total, &uattr->batch.count))
1909 		ret = -EFAULT;
1910 
1911 out:
1912 	kvfree(keys);
1913 	kvfree(values);
1914 	return ret;
1915 }
1916 
1917 static int
1918 htab_percpu_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
1919 			     union bpf_attr __user *uattr)
1920 {
1921 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1922 						  false, true);
1923 }
1924 
1925 static int
1926 htab_percpu_map_lookup_and_delete_batch(struct bpf_map *map,
1927 					const union bpf_attr *attr,
1928 					union bpf_attr __user *uattr)
1929 {
1930 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1931 						  false, true);
1932 }
1933 
1934 static int
1935 htab_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
1936 		      union bpf_attr __user *uattr)
1937 {
1938 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1939 						  false, false);
1940 }
1941 
1942 static int
1943 htab_map_lookup_and_delete_batch(struct bpf_map *map,
1944 				 const union bpf_attr *attr,
1945 				 union bpf_attr __user *uattr)
1946 {
1947 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1948 						  false, false);
1949 }
1950 
1951 static int
1952 htab_lru_percpu_map_lookup_batch(struct bpf_map *map,
1953 				 const union bpf_attr *attr,
1954 				 union bpf_attr __user *uattr)
1955 {
1956 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1957 						  true, true);
1958 }
1959 
1960 static int
1961 htab_lru_percpu_map_lookup_and_delete_batch(struct bpf_map *map,
1962 					    const union bpf_attr *attr,
1963 					    union bpf_attr __user *uattr)
1964 {
1965 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1966 						  true, true);
1967 }
1968 
1969 static int
1970 htab_lru_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
1971 			  union bpf_attr __user *uattr)
1972 {
1973 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1974 						  true, false);
1975 }
1976 
1977 static int
1978 htab_lru_map_lookup_and_delete_batch(struct bpf_map *map,
1979 				     const union bpf_attr *attr,
1980 				     union bpf_attr __user *uattr)
1981 {
1982 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1983 						  true, false);
1984 }
1985 
1986 struct bpf_iter_seq_hash_map_info {
1987 	struct bpf_map *map;
1988 	struct bpf_htab *htab;
1989 	void *percpu_value_buf; // non-zero means percpu hash
1990 	u32 bucket_id;
1991 	u32 skip_elems;
1992 };
1993 
1994 static struct htab_elem *
1995 bpf_hash_map_seq_find_next(struct bpf_iter_seq_hash_map_info *info,
1996 			   struct htab_elem *prev_elem)
1997 {
1998 	const struct bpf_htab *htab = info->htab;
1999 	u32 skip_elems = info->skip_elems;
2000 	u32 bucket_id = info->bucket_id;
2001 	struct hlist_nulls_head *head;
2002 	struct hlist_nulls_node *n;
2003 	struct htab_elem *elem;
2004 	struct bucket *b;
2005 	u32 i, count;
2006 
2007 	if (bucket_id >= htab->n_buckets)
2008 		return NULL;
2009 
2010 	/* try to find next elem in the same bucket */
2011 	if (prev_elem) {
2012 		/* no update/deletion on this bucket, prev_elem should be still valid
2013 		 * and we won't skip elements.
2014 		 */
2015 		n = rcu_dereference_raw(hlist_nulls_next_rcu(&prev_elem->hash_node));
2016 		elem = hlist_nulls_entry_safe(n, struct htab_elem, hash_node);
2017 		if (elem)
2018 			return elem;
2019 
2020 		/* not found, unlock and go to the next bucket */
2021 		b = &htab->buckets[bucket_id++];
2022 		rcu_read_unlock();
2023 		skip_elems = 0;
2024 	}
2025 
2026 	for (i = bucket_id; i < htab->n_buckets; i++) {
2027 		b = &htab->buckets[i];
2028 		rcu_read_lock();
2029 
2030 		count = 0;
2031 		head = &b->head;
2032 		hlist_nulls_for_each_entry_rcu(elem, n, head, hash_node) {
2033 			if (count >= skip_elems) {
2034 				info->bucket_id = i;
2035 				info->skip_elems = count;
2036 				return elem;
2037 			}
2038 			count++;
2039 		}
2040 
2041 		rcu_read_unlock();
2042 		skip_elems = 0;
2043 	}
2044 
2045 	info->bucket_id = i;
2046 	info->skip_elems = 0;
2047 	return NULL;
2048 }
2049 
2050 static void *bpf_hash_map_seq_start(struct seq_file *seq, loff_t *pos)
2051 {
2052 	struct bpf_iter_seq_hash_map_info *info = seq->private;
2053 	struct htab_elem *elem;
2054 
2055 	elem = bpf_hash_map_seq_find_next(info, NULL);
2056 	if (!elem)
2057 		return NULL;
2058 
2059 	if (*pos == 0)
2060 		++*pos;
2061 	return elem;
2062 }
2063 
2064 static void *bpf_hash_map_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2065 {
2066 	struct bpf_iter_seq_hash_map_info *info = seq->private;
2067 
2068 	++*pos;
2069 	++info->skip_elems;
2070 	return bpf_hash_map_seq_find_next(info, v);
2071 }
2072 
2073 static int __bpf_hash_map_seq_show(struct seq_file *seq, struct htab_elem *elem)
2074 {
2075 	struct bpf_iter_seq_hash_map_info *info = seq->private;
2076 	u32 roundup_key_size, roundup_value_size;
2077 	struct bpf_iter__bpf_map_elem ctx = {};
2078 	struct bpf_map *map = info->map;
2079 	struct bpf_iter_meta meta;
2080 	int ret = 0, off = 0, cpu;
2081 	struct bpf_prog *prog;
2082 	void __percpu *pptr;
2083 
2084 	meta.seq = seq;
2085 	prog = bpf_iter_get_info(&meta, elem == NULL);
2086 	if (prog) {
2087 		ctx.meta = &meta;
2088 		ctx.map = info->map;
2089 		if (elem) {
2090 			roundup_key_size = round_up(map->key_size, 8);
2091 			ctx.key = elem->key;
2092 			if (!info->percpu_value_buf) {
2093 				ctx.value = elem->key + roundup_key_size;
2094 			} else {
2095 				roundup_value_size = round_up(map->value_size, 8);
2096 				pptr = htab_elem_get_ptr(elem, map->key_size);
2097 				for_each_possible_cpu(cpu) {
2098 					copy_map_value_long(map, info->percpu_value_buf + off,
2099 							    per_cpu_ptr(pptr, cpu));
2100 					check_and_init_map_value(map, info->percpu_value_buf + off);
2101 					off += roundup_value_size;
2102 				}
2103 				ctx.value = info->percpu_value_buf;
2104 			}
2105 		}
2106 		ret = bpf_iter_run_prog(prog, &ctx);
2107 	}
2108 
2109 	return ret;
2110 }
2111 
2112 static int bpf_hash_map_seq_show(struct seq_file *seq, void *v)
2113 {
2114 	return __bpf_hash_map_seq_show(seq, v);
2115 }
2116 
2117 static void bpf_hash_map_seq_stop(struct seq_file *seq, void *v)
2118 {
2119 	if (!v)
2120 		(void)__bpf_hash_map_seq_show(seq, NULL);
2121 	else
2122 		rcu_read_unlock();
2123 }
2124 
2125 static int bpf_iter_init_hash_map(void *priv_data,
2126 				  struct bpf_iter_aux_info *aux)
2127 {
2128 	struct bpf_iter_seq_hash_map_info *seq_info = priv_data;
2129 	struct bpf_map *map = aux->map;
2130 	void *value_buf;
2131 	u32 buf_size;
2132 
2133 	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
2134 	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
2135 		buf_size = round_up(map->value_size, 8) * num_possible_cpus();
2136 		value_buf = kmalloc(buf_size, GFP_USER | __GFP_NOWARN);
2137 		if (!value_buf)
2138 			return -ENOMEM;
2139 
2140 		seq_info->percpu_value_buf = value_buf;
2141 	}
2142 
2143 	bpf_map_inc_with_uref(map);
2144 	seq_info->map = map;
2145 	seq_info->htab = container_of(map, struct bpf_htab, map);
2146 	return 0;
2147 }
2148 
2149 static void bpf_iter_fini_hash_map(void *priv_data)
2150 {
2151 	struct bpf_iter_seq_hash_map_info *seq_info = priv_data;
2152 
2153 	bpf_map_put_with_uref(seq_info->map);
2154 	kfree(seq_info->percpu_value_buf);
2155 }
2156 
2157 static const struct seq_operations bpf_hash_map_seq_ops = {
2158 	.start	= bpf_hash_map_seq_start,
2159 	.next	= bpf_hash_map_seq_next,
2160 	.stop	= bpf_hash_map_seq_stop,
2161 	.show	= bpf_hash_map_seq_show,
2162 };
2163 
2164 static const struct bpf_iter_seq_info iter_seq_info = {
2165 	.seq_ops		= &bpf_hash_map_seq_ops,
2166 	.init_seq_private	= bpf_iter_init_hash_map,
2167 	.fini_seq_private	= bpf_iter_fini_hash_map,
2168 	.seq_priv_size		= sizeof(struct bpf_iter_seq_hash_map_info),
2169 };
2170 
2171 static long bpf_for_each_hash_elem(struct bpf_map *map, bpf_callback_t callback_fn,
2172 				   void *callback_ctx, u64 flags)
2173 {
2174 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2175 	struct hlist_nulls_head *head;
2176 	struct hlist_nulls_node *n;
2177 	struct htab_elem *elem;
2178 	u32 roundup_key_size;
2179 	int i, num_elems = 0;
2180 	void __percpu *pptr;
2181 	struct bucket *b;
2182 	void *key, *val;
2183 	bool is_percpu;
2184 	u64 ret = 0;
2185 
2186 	if (flags != 0)
2187 		return -EINVAL;
2188 
2189 	is_percpu = htab_is_percpu(htab);
2190 
2191 	roundup_key_size = round_up(map->key_size, 8);
2192 	/* disable migration so percpu value prepared here will be the
2193 	 * same as the one seen by the bpf program with bpf_map_lookup_elem().
2194 	 */
2195 	if (is_percpu)
2196 		migrate_disable();
2197 	for (i = 0; i < htab->n_buckets; i++) {
2198 		b = &htab->buckets[i];
2199 		rcu_read_lock();
2200 		head = &b->head;
2201 		hlist_nulls_for_each_entry_rcu(elem, n, head, hash_node) {
2202 			key = elem->key;
2203 			if (is_percpu) {
2204 				/* current cpu value for percpu map */
2205 				pptr = htab_elem_get_ptr(elem, map->key_size);
2206 				val = this_cpu_ptr(pptr);
2207 			} else {
2208 				val = elem->key + roundup_key_size;
2209 			}
2210 			num_elems++;
2211 			ret = callback_fn((u64)(long)map, (u64)(long)key,
2212 					  (u64)(long)val, (u64)(long)callback_ctx, 0);
2213 			/* return value: 0 - continue, 1 - stop and return */
2214 			if (ret) {
2215 				rcu_read_unlock();
2216 				goto out;
2217 			}
2218 		}
2219 		rcu_read_unlock();
2220 	}
2221 out:
2222 	if (is_percpu)
2223 		migrate_enable();
2224 	return num_elems;
2225 }
2226 
2227 static u64 htab_map_mem_usage(const struct bpf_map *map)
2228 {
2229 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2230 	u32 value_size = round_up(htab->map.value_size, 8);
2231 	bool prealloc = htab_is_prealloc(htab);
2232 	bool percpu = htab_is_percpu(htab);
2233 	bool lru = htab_is_lru(htab);
2234 	u64 num_entries;
2235 	u64 usage = sizeof(struct bpf_htab);
2236 
2237 	usage += sizeof(struct bucket) * htab->n_buckets;
2238 	usage += sizeof(int) * num_possible_cpus() * HASHTAB_MAP_LOCK_COUNT;
2239 	if (prealloc) {
2240 		num_entries = map->max_entries;
2241 		if (htab_has_extra_elems(htab))
2242 			num_entries += num_possible_cpus();
2243 
2244 		usage += htab->elem_size * num_entries;
2245 
2246 		if (percpu)
2247 			usage += value_size * num_possible_cpus() * num_entries;
2248 		else if (!lru)
2249 			usage += sizeof(struct htab_elem *) * num_possible_cpus();
2250 	} else {
2251 #define LLIST_NODE_SZ sizeof(struct llist_node)
2252 
2253 		num_entries = htab->use_percpu_counter ?
2254 					  percpu_counter_sum(&htab->pcount) :
2255 					  atomic_read(&htab->count);
2256 		usage += (htab->elem_size + LLIST_NODE_SZ) * num_entries;
2257 		if (percpu) {
2258 			usage += (LLIST_NODE_SZ + sizeof(void *)) * num_entries;
2259 			usage += value_size * num_possible_cpus() * num_entries;
2260 		}
2261 	}
2262 	return usage;
2263 }
2264 
2265 BTF_ID_LIST_SINGLE(htab_map_btf_ids, struct, bpf_htab)
2266 const struct bpf_map_ops htab_map_ops = {
2267 	.map_meta_equal = bpf_map_meta_equal,
2268 	.map_alloc_check = htab_map_alloc_check,
2269 	.map_alloc = htab_map_alloc,
2270 	.map_free = htab_map_free,
2271 	.map_get_next_key = htab_map_get_next_key,
2272 	.map_release_uref = htab_map_free_timers_and_wq,
2273 	.map_lookup_elem = htab_map_lookup_elem,
2274 	.map_lookup_and_delete_elem = htab_map_lookup_and_delete_elem,
2275 	.map_update_elem = htab_map_update_elem,
2276 	.map_delete_elem = htab_map_delete_elem,
2277 	.map_gen_lookup = htab_map_gen_lookup,
2278 	.map_seq_show_elem = htab_map_seq_show_elem,
2279 	.map_set_for_each_callback_args = map_set_for_each_callback_args,
2280 	.map_for_each_callback = bpf_for_each_hash_elem,
2281 	.map_mem_usage = htab_map_mem_usage,
2282 	BATCH_OPS(htab),
2283 	.map_btf_id = &htab_map_btf_ids[0],
2284 	.iter_seq_info = &iter_seq_info,
2285 };
2286 
2287 const struct bpf_map_ops htab_lru_map_ops = {
2288 	.map_meta_equal = bpf_map_meta_equal,
2289 	.map_alloc_check = htab_map_alloc_check,
2290 	.map_alloc = htab_map_alloc,
2291 	.map_free = htab_map_free,
2292 	.map_get_next_key = htab_map_get_next_key,
2293 	.map_release_uref = htab_map_free_timers_and_wq,
2294 	.map_lookup_elem = htab_lru_map_lookup_elem,
2295 	.map_lookup_and_delete_elem = htab_lru_map_lookup_and_delete_elem,
2296 	.map_lookup_elem_sys_only = htab_lru_map_lookup_elem_sys,
2297 	.map_update_elem = htab_lru_map_update_elem,
2298 	.map_delete_elem = htab_lru_map_delete_elem,
2299 	.map_gen_lookup = htab_lru_map_gen_lookup,
2300 	.map_seq_show_elem = htab_map_seq_show_elem,
2301 	.map_set_for_each_callback_args = map_set_for_each_callback_args,
2302 	.map_for_each_callback = bpf_for_each_hash_elem,
2303 	.map_mem_usage = htab_map_mem_usage,
2304 	BATCH_OPS(htab_lru),
2305 	.map_btf_id = &htab_map_btf_ids[0],
2306 	.iter_seq_info = &iter_seq_info,
2307 };
2308 
2309 /* Called from eBPF program */
2310 static void *htab_percpu_map_lookup_elem(struct bpf_map *map, void *key)
2311 {
2312 	struct htab_elem *l = __htab_map_lookup_elem(map, key);
2313 
2314 	if (l)
2315 		return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size));
2316 	else
2317 		return NULL;
2318 }
2319 
2320 /* inline bpf_map_lookup_elem() call for per-CPU hashmap */
2321 static int htab_percpu_map_gen_lookup(struct bpf_map *map, struct bpf_insn *insn_buf)
2322 {
2323 	struct bpf_insn *insn = insn_buf;
2324 
2325 	if (!bpf_jit_supports_percpu_insn())
2326 		return -EOPNOTSUPP;
2327 
2328 	BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
2329 		     (void *(*)(struct bpf_map *map, void *key))NULL));
2330 	*insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
2331 	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 3);
2332 	*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_0,
2333 				offsetof(struct htab_elem, key) + map->key_size);
2334 	*insn++ = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_0, 0);
2335 	*insn++ = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
2336 
2337 	return insn - insn_buf;
2338 }
2339 
2340 static void *htab_percpu_map_lookup_percpu_elem(struct bpf_map *map, void *key, u32 cpu)
2341 {
2342 	struct htab_elem *l;
2343 
2344 	if (cpu >= nr_cpu_ids)
2345 		return NULL;
2346 
2347 	l = __htab_map_lookup_elem(map, key);
2348 	if (l)
2349 		return per_cpu_ptr(htab_elem_get_ptr(l, map->key_size), cpu);
2350 	else
2351 		return NULL;
2352 }
2353 
2354 static void *htab_lru_percpu_map_lookup_elem(struct bpf_map *map, void *key)
2355 {
2356 	struct htab_elem *l = __htab_map_lookup_elem(map, key);
2357 
2358 	if (l) {
2359 		bpf_lru_node_set_ref(&l->lru_node);
2360 		return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size));
2361 	}
2362 
2363 	return NULL;
2364 }
2365 
2366 static void *htab_lru_percpu_map_lookup_percpu_elem(struct bpf_map *map, void *key, u32 cpu)
2367 {
2368 	struct htab_elem *l;
2369 
2370 	if (cpu >= nr_cpu_ids)
2371 		return NULL;
2372 
2373 	l = __htab_map_lookup_elem(map, key);
2374 	if (l) {
2375 		bpf_lru_node_set_ref(&l->lru_node);
2376 		return per_cpu_ptr(htab_elem_get_ptr(l, map->key_size), cpu);
2377 	}
2378 
2379 	return NULL;
2380 }
2381 
2382 int bpf_percpu_hash_copy(struct bpf_map *map, void *key, void *value)
2383 {
2384 	struct htab_elem *l;
2385 	void __percpu *pptr;
2386 	int ret = -ENOENT;
2387 	int cpu, off = 0;
2388 	u32 size;
2389 
2390 	/* per_cpu areas are zero-filled and bpf programs can only
2391 	 * access 'value_size' of them, so copying rounded areas
2392 	 * will not leak any kernel data
2393 	 */
2394 	size = round_up(map->value_size, 8);
2395 	rcu_read_lock();
2396 	l = __htab_map_lookup_elem(map, key);
2397 	if (!l)
2398 		goto out;
2399 	/* We do not mark LRU map element here in order to not mess up
2400 	 * eviction heuristics when user space does a map walk.
2401 	 */
2402 	pptr = htab_elem_get_ptr(l, map->key_size);
2403 	for_each_possible_cpu(cpu) {
2404 		copy_map_value_long(map, value + off, per_cpu_ptr(pptr, cpu));
2405 		check_and_init_map_value(map, value + off);
2406 		off += size;
2407 	}
2408 	ret = 0;
2409 out:
2410 	rcu_read_unlock();
2411 	return ret;
2412 }
2413 
2414 int bpf_percpu_hash_update(struct bpf_map *map, void *key, void *value,
2415 			   u64 map_flags)
2416 {
2417 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2418 	int ret;
2419 
2420 	rcu_read_lock();
2421 	if (htab_is_lru(htab))
2422 		ret = __htab_lru_percpu_map_update_elem(map, key, value,
2423 							map_flags, true);
2424 	else
2425 		ret = __htab_percpu_map_update_elem(map, key, value, map_flags,
2426 						    true);
2427 	rcu_read_unlock();
2428 
2429 	return ret;
2430 }
2431 
2432 static void htab_percpu_map_seq_show_elem(struct bpf_map *map, void *key,
2433 					  struct seq_file *m)
2434 {
2435 	struct htab_elem *l;
2436 	void __percpu *pptr;
2437 	int cpu;
2438 
2439 	rcu_read_lock();
2440 
2441 	l = __htab_map_lookup_elem(map, key);
2442 	if (!l) {
2443 		rcu_read_unlock();
2444 		return;
2445 	}
2446 
2447 	btf_type_seq_show(map->btf, map->btf_key_type_id, key, m);
2448 	seq_puts(m, ": {\n");
2449 	pptr = htab_elem_get_ptr(l, map->key_size);
2450 	for_each_possible_cpu(cpu) {
2451 		seq_printf(m, "\tcpu%d: ", cpu);
2452 		btf_type_seq_show(map->btf, map->btf_value_type_id,
2453 				  per_cpu_ptr(pptr, cpu), m);
2454 		seq_putc(m, '\n');
2455 	}
2456 	seq_puts(m, "}\n");
2457 
2458 	rcu_read_unlock();
2459 }
2460 
2461 const struct bpf_map_ops htab_percpu_map_ops = {
2462 	.map_meta_equal = bpf_map_meta_equal,
2463 	.map_alloc_check = htab_map_alloc_check,
2464 	.map_alloc = htab_map_alloc,
2465 	.map_free = htab_map_free,
2466 	.map_get_next_key = htab_map_get_next_key,
2467 	.map_lookup_elem = htab_percpu_map_lookup_elem,
2468 	.map_gen_lookup = htab_percpu_map_gen_lookup,
2469 	.map_lookup_and_delete_elem = htab_percpu_map_lookup_and_delete_elem,
2470 	.map_update_elem = htab_percpu_map_update_elem,
2471 	.map_delete_elem = htab_map_delete_elem,
2472 	.map_lookup_percpu_elem = htab_percpu_map_lookup_percpu_elem,
2473 	.map_seq_show_elem = htab_percpu_map_seq_show_elem,
2474 	.map_set_for_each_callback_args = map_set_for_each_callback_args,
2475 	.map_for_each_callback = bpf_for_each_hash_elem,
2476 	.map_mem_usage = htab_map_mem_usage,
2477 	BATCH_OPS(htab_percpu),
2478 	.map_btf_id = &htab_map_btf_ids[0],
2479 	.iter_seq_info = &iter_seq_info,
2480 };
2481 
2482 const struct bpf_map_ops htab_lru_percpu_map_ops = {
2483 	.map_meta_equal = bpf_map_meta_equal,
2484 	.map_alloc_check = htab_map_alloc_check,
2485 	.map_alloc = htab_map_alloc,
2486 	.map_free = htab_map_free,
2487 	.map_get_next_key = htab_map_get_next_key,
2488 	.map_lookup_elem = htab_lru_percpu_map_lookup_elem,
2489 	.map_lookup_and_delete_elem = htab_lru_percpu_map_lookup_and_delete_elem,
2490 	.map_update_elem = htab_lru_percpu_map_update_elem,
2491 	.map_delete_elem = htab_lru_map_delete_elem,
2492 	.map_lookup_percpu_elem = htab_lru_percpu_map_lookup_percpu_elem,
2493 	.map_seq_show_elem = htab_percpu_map_seq_show_elem,
2494 	.map_set_for_each_callback_args = map_set_for_each_callback_args,
2495 	.map_for_each_callback = bpf_for_each_hash_elem,
2496 	.map_mem_usage = htab_map_mem_usage,
2497 	BATCH_OPS(htab_lru_percpu),
2498 	.map_btf_id = &htab_map_btf_ids[0],
2499 	.iter_seq_info = &iter_seq_info,
2500 };
2501 
2502 static int fd_htab_map_alloc_check(union bpf_attr *attr)
2503 {
2504 	if (attr->value_size != sizeof(u32))
2505 		return -EINVAL;
2506 	return htab_map_alloc_check(attr);
2507 }
2508 
2509 static void fd_htab_map_free(struct bpf_map *map)
2510 {
2511 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2512 	struct hlist_nulls_node *n;
2513 	struct hlist_nulls_head *head;
2514 	struct htab_elem *l;
2515 	int i;
2516 
2517 	for (i = 0; i < htab->n_buckets; i++) {
2518 		head = select_bucket(htab, i);
2519 
2520 		hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
2521 			void *ptr = fd_htab_map_get_ptr(map, l);
2522 
2523 			map->ops->map_fd_put_ptr(map, ptr, false);
2524 		}
2525 	}
2526 
2527 	htab_map_free(map);
2528 }
2529 
2530 /* only called from syscall */
2531 int bpf_fd_htab_map_lookup_elem(struct bpf_map *map, void *key, u32 *value)
2532 {
2533 	void **ptr;
2534 	int ret = 0;
2535 
2536 	if (!map->ops->map_fd_sys_lookup_elem)
2537 		return -ENOTSUPP;
2538 
2539 	rcu_read_lock();
2540 	ptr = htab_map_lookup_elem(map, key);
2541 	if (ptr)
2542 		*value = map->ops->map_fd_sys_lookup_elem(READ_ONCE(*ptr));
2543 	else
2544 		ret = -ENOENT;
2545 	rcu_read_unlock();
2546 
2547 	return ret;
2548 }
2549 
2550 /* only called from syscall */
2551 int bpf_fd_htab_map_update_elem(struct bpf_map *map, struct file *map_file,
2552 				void *key, void *value, u64 map_flags)
2553 {
2554 	void *ptr;
2555 	int ret;
2556 	u32 ufd = *(u32 *)value;
2557 
2558 	ptr = map->ops->map_fd_get_ptr(map, map_file, ufd);
2559 	if (IS_ERR(ptr))
2560 		return PTR_ERR(ptr);
2561 
2562 	/* The htab bucket lock is always held during update operations in fd
2563 	 * htab map, and the following rcu_read_lock() is only used to avoid
2564 	 * the WARN_ON_ONCE in htab_map_update_elem().
2565 	 */
2566 	rcu_read_lock();
2567 	ret = htab_map_update_elem(map, key, &ptr, map_flags);
2568 	rcu_read_unlock();
2569 	if (ret)
2570 		map->ops->map_fd_put_ptr(map, ptr, false);
2571 
2572 	return ret;
2573 }
2574 
2575 static struct bpf_map *htab_of_map_alloc(union bpf_attr *attr)
2576 {
2577 	struct bpf_map *map, *inner_map_meta;
2578 
2579 	inner_map_meta = bpf_map_meta_alloc(attr->inner_map_fd);
2580 	if (IS_ERR(inner_map_meta))
2581 		return inner_map_meta;
2582 
2583 	map = htab_map_alloc(attr);
2584 	if (IS_ERR(map)) {
2585 		bpf_map_meta_free(inner_map_meta);
2586 		return map;
2587 	}
2588 
2589 	map->inner_map_meta = inner_map_meta;
2590 
2591 	return map;
2592 }
2593 
2594 static void *htab_of_map_lookup_elem(struct bpf_map *map, void *key)
2595 {
2596 	struct bpf_map **inner_map  = htab_map_lookup_elem(map, key);
2597 
2598 	if (!inner_map)
2599 		return NULL;
2600 
2601 	return READ_ONCE(*inner_map);
2602 }
2603 
2604 static int htab_of_map_gen_lookup(struct bpf_map *map,
2605 				  struct bpf_insn *insn_buf)
2606 {
2607 	struct bpf_insn *insn = insn_buf;
2608 	const int ret = BPF_REG_0;
2609 
2610 	BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
2611 		     (void *(*)(struct bpf_map *map, void *key))NULL));
2612 	*insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
2613 	*insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 2);
2614 	*insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
2615 				offsetof(struct htab_elem, key) +
2616 				round_up(map->key_size, 8));
2617 	*insn++ = BPF_LDX_MEM(BPF_DW, ret, ret, 0);
2618 
2619 	return insn - insn_buf;
2620 }
2621 
2622 static void htab_of_map_free(struct bpf_map *map)
2623 {
2624 	bpf_map_meta_free(map->inner_map_meta);
2625 	fd_htab_map_free(map);
2626 }
2627 
2628 const struct bpf_map_ops htab_of_maps_map_ops = {
2629 	.map_alloc_check = fd_htab_map_alloc_check,
2630 	.map_alloc = htab_of_map_alloc,
2631 	.map_free = htab_of_map_free,
2632 	.map_get_next_key = htab_map_get_next_key,
2633 	.map_lookup_elem = htab_of_map_lookup_elem,
2634 	.map_delete_elem = htab_map_delete_elem,
2635 	.map_fd_get_ptr = bpf_map_fd_get_ptr,
2636 	.map_fd_put_ptr = bpf_map_fd_put_ptr,
2637 	.map_fd_sys_lookup_elem = bpf_map_fd_sys_lookup_elem,
2638 	.map_gen_lookup = htab_of_map_gen_lookup,
2639 	.map_check_btf = map_check_no_btf,
2640 	.map_mem_usage = htab_map_mem_usage,
2641 	BATCH_OPS(htab),
2642 	.map_btf_id = &htab_map_btf_ids[0],
2643 };
2644