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