xref: /linux/kernel/bpf/hashtab.c (revision 0526b56cbc3c489642bd6a5fe4b718dea7ef0ee8)
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 		goto err_lock_bucket;
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 err_lock_bucket:
1240 	if (ret)
1241 		htab_lru_push_free(htab, l_new);
1242 	else if (l_old)
1243 		htab_lru_push_free(htab, l_old);
1244 
1245 	return ret;
1246 }
1247 
1248 static long __htab_percpu_map_update_elem(struct bpf_map *map, void *key,
1249 					  void *value, u64 map_flags,
1250 					  bool onallcpus)
1251 {
1252 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1253 	struct htab_elem *l_new = NULL, *l_old;
1254 	struct hlist_nulls_head *head;
1255 	unsigned long flags;
1256 	struct bucket *b;
1257 	u32 key_size, hash;
1258 	int ret;
1259 
1260 	if (unlikely(map_flags > BPF_EXIST))
1261 		/* unknown flags */
1262 		return -EINVAL;
1263 
1264 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1265 		     !rcu_read_lock_bh_held());
1266 
1267 	key_size = map->key_size;
1268 
1269 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1270 
1271 	b = __select_bucket(htab, hash);
1272 	head = &b->head;
1273 
1274 	ret = htab_lock_bucket(htab, b, hash, &flags);
1275 	if (ret)
1276 		return ret;
1277 
1278 	l_old = lookup_elem_raw(head, hash, key, key_size);
1279 
1280 	ret = check_flags(htab, l_old, map_flags);
1281 	if (ret)
1282 		goto err;
1283 
1284 	if (l_old) {
1285 		/* per-cpu hash map can update value in-place */
1286 		pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size),
1287 				value, onallcpus);
1288 	} else {
1289 		l_new = alloc_htab_elem(htab, key, value, key_size,
1290 					hash, true, onallcpus, NULL);
1291 		if (IS_ERR(l_new)) {
1292 			ret = PTR_ERR(l_new);
1293 			goto err;
1294 		}
1295 		hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1296 	}
1297 	ret = 0;
1298 err:
1299 	htab_unlock_bucket(htab, b, hash, flags);
1300 	return ret;
1301 }
1302 
1303 static long __htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key,
1304 					      void *value, u64 map_flags,
1305 					      bool onallcpus)
1306 {
1307 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1308 	struct htab_elem *l_new = NULL, *l_old;
1309 	struct hlist_nulls_head *head;
1310 	unsigned long flags;
1311 	struct bucket *b;
1312 	u32 key_size, hash;
1313 	int ret;
1314 
1315 	if (unlikely(map_flags > BPF_EXIST))
1316 		/* unknown flags */
1317 		return -EINVAL;
1318 
1319 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1320 		     !rcu_read_lock_bh_held());
1321 
1322 	key_size = map->key_size;
1323 
1324 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1325 
1326 	b = __select_bucket(htab, hash);
1327 	head = &b->head;
1328 
1329 	/* For LRU, we need to alloc before taking bucket's
1330 	 * spinlock because LRU's elem alloc may need
1331 	 * to remove older elem from htab and this removal
1332 	 * operation will need a bucket lock.
1333 	 */
1334 	if (map_flags != BPF_EXIST) {
1335 		l_new = prealloc_lru_pop(htab, key, hash);
1336 		if (!l_new)
1337 			return -ENOMEM;
1338 	}
1339 
1340 	ret = htab_lock_bucket(htab, b, hash, &flags);
1341 	if (ret)
1342 		goto err_lock_bucket;
1343 
1344 	l_old = lookup_elem_raw(head, hash, key, key_size);
1345 
1346 	ret = check_flags(htab, l_old, map_flags);
1347 	if (ret)
1348 		goto err;
1349 
1350 	if (l_old) {
1351 		bpf_lru_node_set_ref(&l_old->lru_node);
1352 
1353 		/* per-cpu hash map can update value in-place */
1354 		pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size),
1355 				value, onallcpus);
1356 	} else {
1357 		pcpu_init_value(htab, htab_elem_get_ptr(l_new, key_size),
1358 				value, onallcpus);
1359 		hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1360 		l_new = NULL;
1361 	}
1362 	ret = 0;
1363 err:
1364 	htab_unlock_bucket(htab, b, hash, flags);
1365 err_lock_bucket:
1366 	if (l_new)
1367 		bpf_lru_push_free(&htab->lru, &l_new->lru_node);
1368 	return ret;
1369 }
1370 
1371 static long htab_percpu_map_update_elem(struct bpf_map *map, void *key,
1372 					void *value, u64 map_flags)
1373 {
1374 	return __htab_percpu_map_update_elem(map, key, value, map_flags, false);
1375 }
1376 
1377 static long htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key,
1378 					    void *value, u64 map_flags)
1379 {
1380 	return __htab_lru_percpu_map_update_elem(map, key, value, map_flags,
1381 						 false);
1382 }
1383 
1384 /* Called from syscall or from eBPF program */
1385 static long htab_map_delete_elem(struct bpf_map *map, void *key)
1386 {
1387 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1388 	struct hlist_nulls_head *head;
1389 	struct bucket *b;
1390 	struct htab_elem *l;
1391 	unsigned long flags;
1392 	u32 hash, key_size;
1393 	int ret;
1394 
1395 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1396 		     !rcu_read_lock_bh_held());
1397 
1398 	key_size = map->key_size;
1399 
1400 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1401 	b = __select_bucket(htab, hash);
1402 	head = &b->head;
1403 
1404 	ret = htab_lock_bucket(htab, b, hash, &flags);
1405 	if (ret)
1406 		return ret;
1407 
1408 	l = lookup_elem_raw(head, hash, key, key_size);
1409 
1410 	if (l) {
1411 		hlist_nulls_del_rcu(&l->hash_node);
1412 		free_htab_elem(htab, l);
1413 	} else {
1414 		ret = -ENOENT;
1415 	}
1416 
1417 	htab_unlock_bucket(htab, b, hash, flags);
1418 	return ret;
1419 }
1420 
1421 static long htab_lru_map_delete_elem(struct bpf_map *map, void *key)
1422 {
1423 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1424 	struct hlist_nulls_head *head;
1425 	struct bucket *b;
1426 	struct htab_elem *l;
1427 	unsigned long flags;
1428 	u32 hash, key_size;
1429 	int ret;
1430 
1431 	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1432 		     !rcu_read_lock_bh_held());
1433 
1434 	key_size = map->key_size;
1435 
1436 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1437 	b = __select_bucket(htab, hash);
1438 	head = &b->head;
1439 
1440 	ret = htab_lock_bucket(htab, b, hash, &flags);
1441 	if (ret)
1442 		return ret;
1443 
1444 	l = lookup_elem_raw(head, hash, key, key_size);
1445 
1446 	if (l)
1447 		hlist_nulls_del_rcu(&l->hash_node);
1448 	else
1449 		ret = -ENOENT;
1450 
1451 	htab_unlock_bucket(htab, b, hash, flags);
1452 	if (l)
1453 		htab_lru_push_free(htab, l);
1454 	return ret;
1455 }
1456 
1457 static void delete_all_elements(struct bpf_htab *htab)
1458 {
1459 	int i;
1460 
1461 	/* It's called from a worker thread, so disable migration here,
1462 	 * since bpf_mem_cache_free() relies on that.
1463 	 */
1464 	migrate_disable();
1465 	for (i = 0; i < htab->n_buckets; i++) {
1466 		struct hlist_nulls_head *head = select_bucket(htab, i);
1467 		struct hlist_nulls_node *n;
1468 		struct htab_elem *l;
1469 
1470 		hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
1471 			hlist_nulls_del_rcu(&l->hash_node);
1472 			htab_elem_free(htab, l);
1473 		}
1474 	}
1475 	migrate_enable();
1476 }
1477 
1478 static void htab_free_malloced_timers(struct bpf_htab *htab)
1479 {
1480 	int i;
1481 
1482 	rcu_read_lock();
1483 	for (i = 0; i < htab->n_buckets; i++) {
1484 		struct hlist_nulls_head *head = select_bucket(htab, i);
1485 		struct hlist_nulls_node *n;
1486 		struct htab_elem *l;
1487 
1488 		hlist_nulls_for_each_entry(l, n, head, hash_node) {
1489 			/* We only free timer on uref dropping to zero */
1490 			bpf_obj_free_timer(htab->map.record, l->key + round_up(htab->map.key_size, 8));
1491 		}
1492 		cond_resched_rcu();
1493 	}
1494 	rcu_read_unlock();
1495 }
1496 
1497 static void htab_map_free_timers(struct bpf_map *map)
1498 {
1499 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1500 
1501 	/* We only free timer on uref dropping to zero */
1502 	if (!btf_record_has_field(htab->map.record, BPF_TIMER))
1503 		return;
1504 	if (!htab_is_prealloc(htab))
1505 		htab_free_malloced_timers(htab);
1506 	else
1507 		htab_free_prealloced_timers(htab);
1508 }
1509 
1510 /* Called when map->refcnt goes to zero, either from workqueue or from syscall */
1511 static void htab_map_free(struct bpf_map *map)
1512 {
1513 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1514 	int i;
1515 
1516 	/* bpf_free_used_maps() or close(map_fd) will trigger this map_free callback.
1517 	 * bpf_free_used_maps() is called after bpf prog is no longer executing.
1518 	 * There is no need to synchronize_rcu() here to protect map elements.
1519 	 */
1520 
1521 	/* htab no longer uses call_rcu() directly. bpf_mem_alloc does it
1522 	 * underneath and is reponsible for waiting for callbacks to finish
1523 	 * during bpf_mem_alloc_destroy().
1524 	 */
1525 	if (!htab_is_prealloc(htab)) {
1526 		delete_all_elements(htab);
1527 	} else {
1528 		htab_free_prealloced_fields(htab);
1529 		prealloc_destroy(htab);
1530 	}
1531 
1532 	free_percpu(htab->extra_elems);
1533 	bpf_map_area_free(htab->buckets);
1534 	bpf_mem_alloc_destroy(&htab->pcpu_ma);
1535 	bpf_mem_alloc_destroy(&htab->ma);
1536 	if (htab->use_percpu_counter)
1537 		percpu_counter_destroy(&htab->pcount);
1538 	for (i = 0; i < HASHTAB_MAP_LOCK_COUNT; i++)
1539 		free_percpu(htab->map_locked[i]);
1540 	lockdep_unregister_key(&htab->lockdep_key);
1541 	bpf_map_area_free(htab);
1542 }
1543 
1544 static void htab_map_seq_show_elem(struct bpf_map *map, void *key,
1545 				   struct seq_file *m)
1546 {
1547 	void *value;
1548 
1549 	rcu_read_lock();
1550 
1551 	value = htab_map_lookup_elem(map, key);
1552 	if (!value) {
1553 		rcu_read_unlock();
1554 		return;
1555 	}
1556 
1557 	btf_type_seq_show(map->btf, map->btf_key_type_id, key, m);
1558 	seq_puts(m, ": ");
1559 	btf_type_seq_show(map->btf, map->btf_value_type_id, value, m);
1560 	seq_puts(m, "\n");
1561 
1562 	rcu_read_unlock();
1563 }
1564 
1565 static int __htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
1566 					     void *value, bool is_lru_map,
1567 					     bool is_percpu, u64 flags)
1568 {
1569 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1570 	struct hlist_nulls_head *head;
1571 	unsigned long bflags;
1572 	struct htab_elem *l;
1573 	u32 hash, key_size;
1574 	struct bucket *b;
1575 	int ret;
1576 
1577 	key_size = map->key_size;
1578 
1579 	hash = htab_map_hash(key, key_size, htab->hashrnd);
1580 	b = __select_bucket(htab, hash);
1581 	head = &b->head;
1582 
1583 	ret = htab_lock_bucket(htab, b, hash, &bflags);
1584 	if (ret)
1585 		return ret;
1586 
1587 	l = lookup_elem_raw(head, hash, key, key_size);
1588 	if (!l) {
1589 		ret = -ENOENT;
1590 	} else {
1591 		if (is_percpu) {
1592 			u32 roundup_value_size = round_up(map->value_size, 8);
1593 			void __percpu *pptr;
1594 			int off = 0, cpu;
1595 
1596 			pptr = htab_elem_get_ptr(l, key_size);
1597 			for_each_possible_cpu(cpu) {
1598 				copy_map_value_long(&htab->map, value + off, per_cpu_ptr(pptr, cpu));
1599 				check_and_init_map_value(&htab->map, value + off);
1600 				off += roundup_value_size;
1601 			}
1602 		} else {
1603 			u32 roundup_key_size = round_up(map->key_size, 8);
1604 
1605 			if (flags & BPF_F_LOCK)
1606 				copy_map_value_locked(map, value, l->key +
1607 						      roundup_key_size,
1608 						      true);
1609 			else
1610 				copy_map_value(map, value, l->key +
1611 					       roundup_key_size);
1612 			/* Zeroing special fields in the temp buffer */
1613 			check_and_init_map_value(map, value);
1614 		}
1615 
1616 		hlist_nulls_del_rcu(&l->hash_node);
1617 		if (!is_lru_map)
1618 			free_htab_elem(htab, l);
1619 	}
1620 
1621 	htab_unlock_bucket(htab, b, hash, bflags);
1622 
1623 	if (is_lru_map && l)
1624 		htab_lru_push_free(htab, l);
1625 
1626 	return ret;
1627 }
1628 
1629 static int htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
1630 					   void *value, u64 flags)
1631 {
1632 	return __htab_map_lookup_and_delete_elem(map, key, value, false, false,
1633 						 flags);
1634 }
1635 
1636 static int htab_percpu_map_lookup_and_delete_elem(struct bpf_map *map,
1637 						  void *key, void *value,
1638 						  u64 flags)
1639 {
1640 	return __htab_map_lookup_and_delete_elem(map, key, value, false, true,
1641 						 flags);
1642 }
1643 
1644 static int htab_lru_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
1645 					       void *value, u64 flags)
1646 {
1647 	return __htab_map_lookup_and_delete_elem(map, key, value, true, false,
1648 						 flags);
1649 }
1650 
1651 static int htab_lru_percpu_map_lookup_and_delete_elem(struct bpf_map *map,
1652 						      void *key, void *value,
1653 						      u64 flags)
1654 {
1655 	return __htab_map_lookup_and_delete_elem(map, key, value, true, true,
1656 						 flags);
1657 }
1658 
1659 static int
1660 __htab_map_lookup_and_delete_batch(struct bpf_map *map,
1661 				   const union bpf_attr *attr,
1662 				   union bpf_attr __user *uattr,
1663 				   bool do_delete, bool is_lru_map,
1664 				   bool is_percpu)
1665 {
1666 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1667 	u32 bucket_cnt, total, key_size, value_size, roundup_key_size;
1668 	void *keys = NULL, *values = NULL, *value, *dst_key, *dst_val;
1669 	void __user *uvalues = u64_to_user_ptr(attr->batch.values);
1670 	void __user *ukeys = u64_to_user_ptr(attr->batch.keys);
1671 	void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1672 	u32 batch, max_count, size, bucket_size, map_id;
1673 	struct htab_elem *node_to_free = NULL;
1674 	u64 elem_map_flags, map_flags;
1675 	struct hlist_nulls_head *head;
1676 	struct hlist_nulls_node *n;
1677 	unsigned long flags = 0;
1678 	bool locked = false;
1679 	struct htab_elem *l;
1680 	struct bucket *b;
1681 	int ret = 0;
1682 
1683 	elem_map_flags = attr->batch.elem_flags;
1684 	if ((elem_map_flags & ~BPF_F_LOCK) ||
1685 	    ((elem_map_flags & BPF_F_LOCK) && !btf_record_has_field(map->record, BPF_SPIN_LOCK)))
1686 		return -EINVAL;
1687 
1688 	map_flags = attr->batch.flags;
1689 	if (map_flags)
1690 		return -EINVAL;
1691 
1692 	max_count = attr->batch.count;
1693 	if (!max_count)
1694 		return 0;
1695 
1696 	if (put_user(0, &uattr->batch.count))
1697 		return -EFAULT;
1698 
1699 	batch = 0;
1700 	if (ubatch && copy_from_user(&batch, ubatch, sizeof(batch)))
1701 		return -EFAULT;
1702 
1703 	if (batch >= htab->n_buckets)
1704 		return -ENOENT;
1705 
1706 	key_size = htab->map.key_size;
1707 	roundup_key_size = round_up(htab->map.key_size, 8);
1708 	value_size = htab->map.value_size;
1709 	size = round_up(value_size, 8);
1710 	if (is_percpu)
1711 		value_size = size * num_possible_cpus();
1712 	total = 0;
1713 	/* while experimenting with hash tables with sizes ranging from 10 to
1714 	 * 1000, it was observed that a bucket can have up to 5 entries.
1715 	 */
1716 	bucket_size = 5;
1717 
1718 alloc:
1719 	/* We cannot do copy_from_user or copy_to_user inside
1720 	 * the rcu_read_lock. Allocate enough space here.
1721 	 */
1722 	keys = kvmalloc_array(key_size, bucket_size, GFP_USER | __GFP_NOWARN);
1723 	values = kvmalloc_array(value_size, bucket_size, GFP_USER | __GFP_NOWARN);
1724 	if (!keys || !values) {
1725 		ret = -ENOMEM;
1726 		goto after_loop;
1727 	}
1728 
1729 again:
1730 	bpf_disable_instrumentation();
1731 	rcu_read_lock();
1732 again_nocopy:
1733 	dst_key = keys;
1734 	dst_val = values;
1735 	b = &htab->buckets[batch];
1736 	head = &b->head;
1737 	/* do not grab the lock unless need it (bucket_cnt > 0). */
1738 	if (locked) {
1739 		ret = htab_lock_bucket(htab, b, batch, &flags);
1740 		if (ret) {
1741 			rcu_read_unlock();
1742 			bpf_enable_instrumentation();
1743 			goto after_loop;
1744 		}
1745 	}
1746 
1747 	bucket_cnt = 0;
1748 	hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
1749 		bucket_cnt++;
1750 
1751 	if (bucket_cnt && !locked) {
1752 		locked = true;
1753 		goto again_nocopy;
1754 	}
1755 
1756 	if (bucket_cnt > (max_count - total)) {
1757 		if (total == 0)
1758 			ret = -ENOSPC;
1759 		/* Note that since bucket_cnt > 0 here, it is implicit
1760 		 * that the locked was grabbed, so release it.
1761 		 */
1762 		htab_unlock_bucket(htab, b, batch, flags);
1763 		rcu_read_unlock();
1764 		bpf_enable_instrumentation();
1765 		goto after_loop;
1766 	}
1767 
1768 	if (bucket_cnt > bucket_size) {
1769 		bucket_size = bucket_cnt;
1770 		/* Note that since bucket_cnt > 0 here, it is implicit
1771 		 * that the locked was grabbed, so release it.
1772 		 */
1773 		htab_unlock_bucket(htab, b, batch, flags);
1774 		rcu_read_unlock();
1775 		bpf_enable_instrumentation();
1776 		kvfree(keys);
1777 		kvfree(values);
1778 		goto alloc;
1779 	}
1780 
1781 	/* Next block is only safe to run if you have grabbed the lock */
1782 	if (!locked)
1783 		goto next_batch;
1784 
1785 	hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
1786 		memcpy(dst_key, l->key, key_size);
1787 
1788 		if (is_percpu) {
1789 			int off = 0, cpu;
1790 			void __percpu *pptr;
1791 
1792 			pptr = htab_elem_get_ptr(l, map->key_size);
1793 			for_each_possible_cpu(cpu) {
1794 				copy_map_value_long(&htab->map, dst_val + off, per_cpu_ptr(pptr, cpu));
1795 				check_and_init_map_value(&htab->map, dst_val + off);
1796 				off += size;
1797 			}
1798 		} else {
1799 			value = l->key + roundup_key_size;
1800 			if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
1801 				struct bpf_map **inner_map = value;
1802 
1803 				 /* Actual value is the id of the inner map */
1804 				map_id = map->ops->map_fd_sys_lookup_elem(*inner_map);
1805 				value = &map_id;
1806 			}
1807 
1808 			if (elem_map_flags & BPF_F_LOCK)
1809 				copy_map_value_locked(map, dst_val, value,
1810 						      true);
1811 			else
1812 				copy_map_value(map, dst_val, value);
1813 			/* Zeroing special fields in the temp buffer */
1814 			check_and_init_map_value(map, dst_val);
1815 		}
1816 		if (do_delete) {
1817 			hlist_nulls_del_rcu(&l->hash_node);
1818 
1819 			/* bpf_lru_push_free() will acquire lru_lock, which
1820 			 * may cause deadlock. See comments in function
1821 			 * prealloc_lru_pop(). Let us do bpf_lru_push_free()
1822 			 * after releasing the bucket lock.
1823 			 */
1824 			if (is_lru_map) {
1825 				l->batch_flink = node_to_free;
1826 				node_to_free = l;
1827 			} else {
1828 				free_htab_elem(htab, l);
1829 			}
1830 		}
1831 		dst_key += key_size;
1832 		dst_val += value_size;
1833 	}
1834 
1835 	htab_unlock_bucket(htab, b, batch, flags);
1836 	locked = false;
1837 
1838 	while (node_to_free) {
1839 		l = node_to_free;
1840 		node_to_free = node_to_free->batch_flink;
1841 		htab_lru_push_free(htab, l);
1842 	}
1843 
1844 next_batch:
1845 	/* If we are not copying data, we can go to next bucket and avoid
1846 	 * unlocking the rcu.
1847 	 */
1848 	if (!bucket_cnt && (batch + 1 < htab->n_buckets)) {
1849 		batch++;
1850 		goto again_nocopy;
1851 	}
1852 
1853 	rcu_read_unlock();
1854 	bpf_enable_instrumentation();
1855 	if (bucket_cnt && (copy_to_user(ukeys + total * key_size, keys,
1856 	    key_size * bucket_cnt) ||
1857 	    copy_to_user(uvalues + total * value_size, values,
1858 	    value_size * bucket_cnt))) {
1859 		ret = -EFAULT;
1860 		goto after_loop;
1861 	}
1862 
1863 	total += bucket_cnt;
1864 	batch++;
1865 	if (batch >= htab->n_buckets) {
1866 		ret = -ENOENT;
1867 		goto after_loop;
1868 	}
1869 	goto again;
1870 
1871 after_loop:
1872 	if (ret == -EFAULT)
1873 		goto out;
1874 
1875 	/* copy # of entries and next batch */
1876 	ubatch = u64_to_user_ptr(attr->batch.out_batch);
1877 	if (copy_to_user(ubatch, &batch, sizeof(batch)) ||
1878 	    put_user(total, &uattr->batch.count))
1879 		ret = -EFAULT;
1880 
1881 out:
1882 	kvfree(keys);
1883 	kvfree(values);
1884 	return ret;
1885 }
1886 
1887 static int
1888 htab_percpu_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
1889 			     union bpf_attr __user *uattr)
1890 {
1891 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1892 						  false, true);
1893 }
1894 
1895 static int
1896 htab_percpu_map_lookup_and_delete_batch(struct bpf_map *map,
1897 					const union bpf_attr *attr,
1898 					union bpf_attr __user *uattr)
1899 {
1900 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1901 						  false, true);
1902 }
1903 
1904 static int
1905 htab_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
1906 		      union bpf_attr __user *uattr)
1907 {
1908 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1909 						  false, false);
1910 }
1911 
1912 static int
1913 htab_map_lookup_and_delete_batch(struct bpf_map *map,
1914 				 const union bpf_attr *attr,
1915 				 union bpf_attr __user *uattr)
1916 {
1917 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1918 						  false, false);
1919 }
1920 
1921 static int
1922 htab_lru_percpu_map_lookup_batch(struct bpf_map *map,
1923 				 const union bpf_attr *attr,
1924 				 union bpf_attr __user *uattr)
1925 {
1926 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1927 						  true, true);
1928 }
1929 
1930 static int
1931 htab_lru_percpu_map_lookup_and_delete_batch(struct bpf_map *map,
1932 					    const union bpf_attr *attr,
1933 					    union bpf_attr __user *uattr)
1934 {
1935 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1936 						  true, true);
1937 }
1938 
1939 static int
1940 htab_lru_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
1941 			  union bpf_attr __user *uattr)
1942 {
1943 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1944 						  true, false);
1945 }
1946 
1947 static int
1948 htab_lru_map_lookup_and_delete_batch(struct bpf_map *map,
1949 				     const union bpf_attr *attr,
1950 				     union bpf_attr __user *uattr)
1951 {
1952 	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1953 						  true, false);
1954 }
1955 
1956 struct bpf_iter_seq_hash_map_info {
1957 	struct bpf_map *map;
1958 	struct bpf_htab *htab;
1959 	void *percpu_value_buf; // non-zero means percpu hash
1960 	u32 bucket_id;
1961 	u32 skip_elems;
1962 };
1963 
1964 static struct htab_elem *
1965 bpf_hash_map_seq_find_next(struct bpf_iter_seq_hash_map_info *info,
1966 			   struct htab_elem *prev_elem)
1967 {
1968 	const struct bpf_htab *htab = info->htab;
1969 	u32 skip_elems = info->skip_elems;
1970 	u32 bucket_id = info->bucket_id;
1971 	struct hlist_nulls_head *head;
1972 	struct hlist_nulls_node *n;
1973 	struct htab_elem *elem;
1974 	struct bucket *b;
1975 	u32 i, count;
1976 
1977 	if (bucket_id >= htab->n_buckets)
1978 		return NULL;
1979 
1980 	/* try to find next elem in the same bucket */
1981 	if (prev_elem) {
1982 		/* no update/deletion on this bucket, prev_elem should be still valid
1983 		 * and we won't skip elements.
1984 		 */
1985 		n = rcu_dereference_raw(hlist_nulls_next_rcu(&prev_elem->hash_node));
1986 		elem = hlist_nulls_entry_safe(n, struct htab_elem, hash_node);
1987 		if (elem)
1988 			return elem;
1989 
1990 		/* not found, unlock and go to the next bucket */
1991 		b = &htab->buckets[bucket_id++];
1992 		rcu_read_unlock();
1993 		skip_elems = 0;
1994 	}
1995 
1996 	for (i = bucket_id; i < htab->n_buckets; i++) {
1997 		b = &htab->buckets[i];
1998 		rcu_read_lock();
1999 
2000 		count = 0;
2001 		head = &b->head;
2002 		hlist_nulls_for_each_entry_rcu(elem, n, head, hash_node) {
2003 			if (count >= skip_elems) {
2004 				info->bucket_id = i;
2005 				info->skip_elems = count;
2006 				return elem;
2007 			}
2008 			count++;
2009 		}
2010 
2011 		rcu_read_unlock();
2012 		skip_elems = 0;
2013 	}
2014 
2015 	info->bucket_id = i;
2016 	info->skip_elems = 0;
2017 	return NULL;
2018 }
2019 
2020 static void *bpf_hash_map_seq_start(struct seq_file *seq, loff_t *pos)
2021 {
2022 	struct bpf_iter_seq_hash_map_info *info = seq->private;
2023 	struct htab_elem *elem;
2024 
2025 	elem = bpf_hash_map_seq_find_next(info, NULL);
2026 	if (!elem)
2027 		return NULL;
2028 
2029 	if (*pos == 0)
2030 		++*pos;
2031 	return elem;
2032 }
2033 
2034 static void *bpf_hash_map_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2035 {
2036 	struct bpf_iter_seq_hash_map_info *info = seq->private;
2037 
2038 	++*pos;
2039 	++info->skip_elems;
2040 	return bpf_hash_map_seq_find_next(info, v);
2041 }
2042 
2043 static int __bpf_hash_map_seq_show(struct seq_file *seq, struct htab_elem *elem)
2044 {
2045 	struct bpf_iter_seq_hash_map_info *info = seq->private;
2046 	u32 roundup_key_size, roundup_value_size;
2047 	struct bpf_iter__bpf_map_elem ctx = {};
2048 	struct bpf_map *map = info->map;
2049 	struct bpf_iter_meta meta;
2050 	int ret = 0, off = 0, cpu;
2051 	struct bpf_prog *prog;
2052 	void __percpu *pptr;
2053 
2054 	meta.seq = seq;
2055 	prog = bpf_iter_get_info(&meta, elem == NULL);
2056 	if (prog) {
2057 		ctx.meta = &meta;
2058 		ctx.map = info->map;
2059 		if (elem) {
2060 			roundup_key_size = round_up(map->key_size, 8);
2061 			ctx.key = elem->key;
2062 			if (!info->percpu_value_buf) {
2063 				ctx.value = elem->key + roundup_key_size;
2064 			} else {
2065 				roundup_value_size = round_up(map->value_size, 8);
2066 				pptr = htab_elem_get_ptr(elem, map->key_size);
2067 				for_each_possible_cpu(cpu) {
2068 					copy_map_value_long(map, info->percpu_value_buf + off,
2069 							    per_cpu_ptr(pptr, cpu));
2070 					check_and_init_map_value(map, info->percpu_value_buf + off);
2071 					off += roundup_value_size;
2072 				}
2073 				ctx.value = info->percpu_value_buf;
2074 			}
2075 		}
2076 		ret = bpf_iter_run_prog(prog, &ctx);
2077 	}
2078 
2079 	return ret;
2080 }
2081 
2082 static int bpf_hash_map_seq_show(struct seq_file *seq, void *v)
2083 {
2084 	return __bpf_hash_map_seq_show(seq, v);
2085 }
2086 
2087 static void bpf_hash_map_seq_stop(struct seq_file *seq, void *v)
2088 {
2089 	if (!v)
2090 		(void)__bpf_hash_map_seq_show(seq, NULL);
2091 	else
2092 		rcu_read_unlock();
2093 }
2094 
2095 static int bpf_iter_init_hash_map(void *priv_data,
2096 				  struct bpf_iter_aux_info *aux)
2097 {
2098 	struct bpf_iter_seq_hash_map_info *seq_info = priv_data;
2099 	struct bpf_map *map = aux->map;
2100 	void *value_buf;
2101 	u32 buf_size;
2102 
2103 	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
2104 	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
2105 		buf_size = round_up(map->value_size, 8) * num_possible_cpus();
2106 		value_buf = kmalloc(buf_size, GFP_USER | __GFP_NOWARN);
2107 		if (!value_buf)
2108 			return -ENOMEM;
2109 
2110 		seq_info->percpu_value_buf = value_buf;
2111 	}
2112 
2113 	bpf_map_inc_with_uref(map);
2114 	seq_info->map = map;
2115 	seq_info->htab = container_of(map, struct bpf_htab, map);
2116 	return 0;
2117 }
2118 
2119 static void bpf_iter_fini_hash_map(void *priv_data)
2120 {
2121 	struct bpf_iter_seq_hash_map_info *seq_info = priv_data;
2122 
2123 	bpf_map_put_with_uref(seq_info->map);
2124 	kfree(seq_info->percpu_value_buf);
2125 }
2126 
2127 static const struct seq_operations bpf_hash_map_seq_ops = {
2128 	.start	= bpf_hash_map_seq_start,
2129 	.next	= bpf_hash_map_seq_next,
2130 	.stop	= bpf_hash_map_seq_stop,
2131 	.show	= bpf_hash_map_seq_show,
2132 };
2133 
2134 static const struct bpf_iter_seq_info iter_seq_info = {
2135 	.seq_ops		= &bpf_hash_map_seq_ops,
2136 	.init_seq_private	= bpf_iter_init_hash_map,
2137 	.fini_seq_private	= bpf_iter_fini_hash_map,
2138 	.seq_priv_size		= sizeof(struct bpf_iter_seq_hash_map_info),
2139 };
2140 
2141 static long bpf_for_each_hash_elem(struct bpf_map *map, bpf_callback_t callback_fn,
2142 				   void *callback_ctx, u64 flags)
2143 {
2144 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2145 	struct hlist_nulls_head *head;
2146 	struct hlist_nulls_node *n;
2147 	struct htab_elem *elem;
2148 	u32 roundup_key_size;
2149 	int i, num_elems = 0;
2150 	void __percpu *pptr;
2151 	struct bucket *b;
2152 	void *key, *val;
2153 	bool is_percpu;
2154 	u64 ret = 0;
2155 
2156 	if (flags != 0)
2157 		return -EINVAL;
2158 
2159 	is_percpu = htab_is_percpu(htab);
2160 
2161 	roundup_key_size = round_up(map->key_size, 8);
2162 	/* disable migration so percpu value prepared here will be the
2163 	 * same as the one seen by the bpf program with bpf_map_lookup_elem().
2164 	 */
2165 	if (is_percpu)
2166 		migrate_disable();
2167 	for (i = 0; i < htab->n_buckets; i++) {
2168 		b = &htab->buckets[i];
2169 		rcu_read_lock();
2170 		head = &b->head;
2171 		hlist_nulls_for_each_entry_rcu(elem, n, head, hash_node) {
2172 			key = elem->key;
2173 			if (is_percpu) {
2174 				/* current cpu value for percpu map */
2175 				pptr = htab_elem_get_ptr(elem, map->key_size);
2176 				val = this_cpu_ptr(pptr);
2177 			} else {
2178 				val = elem->key + roundup_key_size;
2179 			}
2180 			num_elems++;
2181 			ret = callback_fn((u64)(long)map, (u64)(long)key,
2182 					  (u64)(long)val, (u64)(long)callback_ctx, 0);
2183 			/* return value: 0 - continue, 1 - stop and return */
2184 			if (ret) {
2185 				rcu_read_unlock();
2186 				goto out;
2187 			}
2188 		}
2189 		rcu_read_unlock();
2190 	}
2191 out:
2192 	if (is_percpu)
2193 		migrate_enable();
2194 	return num_elems;
2195 }
2196 
2197 static u64 htab_map_mem_usage(const struct bpf_map *map)
2198 {
2199 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2200 	u32 value_size = round_up(htab->map.value_size, 8);
2201 	bool prealloc = htab_is_prealloc(htab);
2202 	bool percpu = htab_is_percpu(htab);
2203 	bool lru = htab_is_lru(htab);
2204 	u64 num_entries;
2205 	u64 usage = sizeof(struct bpf_htab);
2206 
2207 	usage += sizeof(struct bucket) * htab->n_buckets;
2208 	usage += sizeof(int) * num_possible_cpus() * HASHTAB_MAP_LOCK_COUNT;
2209 	if (prealloc) {
2210 		num_entries = map->max_entries;
2211 		if (htab_has_extra_elems(htab))
2212 			num_entries += num_possible_cpus();
2213 
2214 		usage += htab->elem_size * num_entries;
2215 
2216 		if (percpu)
2217 			usage += value_size * num_possible_cpus() * num_entries;
2218 		else if (!lru)
2219 			usage += sizeof(struct htab_elem *) * num_possible_cpus();
2220 	} else {
2221 #define LLIST_NODE_SZ sizeof(struct llist_node)
2222 
2223 		num_entries = htab->use_percpu_counter ?
2224 					  percpu_counter_sum(&htab->pcount) :
2225 					  atomic_read(&htab->count);
2226 		usage += (htab->elem_size + LLIST_NODE_SZ) * num_entries;
2227 		if (percpu) {
2228 			usage += (LLIST_NODE_SZ + sizeof(void *)) * num_entries;
2229 			usage += value_size * num_possible_cpus() * num_entries;
2230 		}
2231 	}
2232 	return usage;
2233 }
2234 
2235 BTF_ID_LIST_SINGLE(htab_map_btf_ids, struct, bpf_htab)
2236 const struct bpf_map_ops htab_map_ops = {
2237 	.map_meta_equal = bpf_map_meta_equal,
2238 	.map_alloc_check = htab_map_alloc_check,
2239 	.map_alloc = htab_map_alloc,
2240 	.map_free = htab_map_free,
2241 	.map_get_next_key = htab_map_get_next_key,
2242 	.map_release_uref = htab_map_free_timers,
2243 	.map_lookup_elem = htab_map_lookup_elem,
2244 	.map_lookup_and_delete_elem = htab_map_lookup_and_delete_elem,
2245 	.map_update_elem = htab_map_update_elem,
2246 	.map_delete_elem = htab_map_delete_elem,
2247 	.map_gen_lookup = htab_map_gen_lookup,
2248 	.map_seq_show_elem = htab_map_seq_show_elem,
2249 	.map_set_for_each_callback_args = map_set_for_each_callback_args,
2250 	.map_for_each_callback = bpf_for_each_hash_elem,
2251 	.map_mem_usage = htab_map_mem_usage,
2252 	BATCH_OPS(htab),
2253 	.map_btf_id = &htab_map_btf_ids[0],
2254 	.iter_seq_info = &iter_seq_info,
2255 };
2256 
2257 const struct bpf_map_ops htab_lru_map_ops = {
2258 	.map_meta_equal = bpf_map_meta_equal,
2259 	.map_alloc_check = htab_map_alloc_check,
2260 	.map_alloc = htab_map_alloc,
2261 	.map_free = htab_map_free,
2262 	.map_get_next_key = htab_map_get_next_key,
2263 	.map_release_uref = htab_map_free_timers,
2264 	.map_lookup_elem = htab_lru_map_lookup_elem,
2265 	.map_lookup_and_delete_elem = htab_lru_map_lookup_and_delete_elem,
2266 	.map_lookup_elem_sys_only = htab_lru_map_lookup_elem_sys,
2267 	.map_update_elem = htab_lru_map_update_elem,
2268 	.map_delete_elem = htab_lru_map_delete_elem,
2269 	.map_gen_lookup = htab_lru_map_gen_lookup,
2270 	.map_seq_show_elem = htab_map_seq_show_elem,
2271 	.map_set_for_each_callback_args = map_set_for_each_callback_args,
2272 	.map_for_each_callback = bpf_for_each_hash_elem,
2273 	.map_mem_usage = htab_map_mem_usage,
2274 	BATCH_OPS(htab_lru),
2275 	.map_btf_id = &htab_map_btf_ids[0],
2276 	.iter_seq_info = &iter_seq_info,
2277 };
2278 
2279 /* Called from eBPF program */
2280 static void *htab_percpu_map_lookup_elem(struct bpf_map *map, void *key)
2281 {
2282 	struct htab_elem *l = __htab_map_lookup_elem(map, key);
2283 
2284 	if (l)
2285 		return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size));
2286 	else
2287 		return NULL;
2288 }
2289 
2290 static void *htab_percpu_map_lookup_percpu_elem(struct bpf_map *map, void *key, u32 cpu)
2291 {
2292 	struct htab_elem *l;
2293 
2294 	if (cpu >= nr_cpu_ids)
2295 		return NULL;
2296 
2297 	l = __htab_map_lookup_elem(map, key);
2298 	if (l)
2299 		return per_cpu_ptr(htab_elem_get_ptr(l, map->key_size), cpu);
2300 	else
2301 		return NULL;
2302 }
2303 
2304 static void *htab_lru_percpu_map_lookup_elem(struct bpf_map *map, void *key)
2305 {
2306 	struct htab_elem *l = __htab_map_lookup_elem(map, key);
2307 
2308 	if (l) {
2309 		bpf_lru_node_set_ref(&l->lru_node);
2310 		return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size));
2311 	}
2312 
2313 	return NULL;
2314 }
2315 
2316 static void *htab_lru_percpu_map_lookup_percpu_elem(struct bpf_map *map, void *key, u32 cpu)
2317 {
2318 	struct htab_elem *l;
2319 
2320 	if (cpu >= nr_cpu_ids)
2321 		return NULL;
2322 
2323 	l = __htab_map_lookup_elem(map, key);
2324 	if (l) {
2325 		bpf_lru_node_set_ref(&l->lru_node);
2326 		return per_cpu_ptr(htab_elem_get_ptr(l, map->key_size), cpu);
2327 	}
2328 
2329 	return NULL;
2330 }
2331 
2332 int bpf_percpu_hash_copy(struct bpf_map *map, void *key, void *value)
2333 {
2334 	struct htab_elem *l;
2335 	void __percpu *pptr;
2336 	int ret = -ENOENT;
2337 	int cpu, off = 0;
2338 	u32 size;
2339 
2340 	/* per_cpu areas are zero-filled and bpf programs can only
2341 	 * access 'value_size' of them, so copying rounded areas
2342 	 * will not leak any kernel data
2343 	 */
2344 	size = round_up(map->value_size, 8);
2345 	rcu_read_lock();
2346 	l = __htab_map_lookup_elem(map, key);
2347 	if (!l)
2348 		goto out;
2349 	/* We do not mark LRU map element here in order to not mess up
2350 	 * eviction heuristics when user space does a map walk.
2351 	 */
2352 	pptr = htab_elem_get_ptr(l, map->key_size);
2353 	for_each_possible_cpu(cpu) {
2354 		copy_map_value_long(map, value + off, per_cpu_ptr(pptr, cpu));
2355 		check_and_init_map_value(map, value + off);
2356 		off += size;
2357 	}
2358 	ret = 0;
2359 out:
2360 	rcu_read_unlock();
2361 	return ret;
2362 }
2363 
2364 int bpf_percpu_hash_update(struct bpf_map *map, void *key, void *value,
2365 			   u64 map_flags)
2366 {
2367 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2368 	int ret;
2369 
2370 	rcu_read_lock();
2371 	if (htab_is_lru(htab))
2372 		ret = __htab_lru_percpu_map_update_elem(map, key, value,
2373 							map_flags, true);
2374 	else
2375 		ret = __htab_percpu_map_update_elem(map, key, value, map_flags,
2376 						    true);
2377 	rcu_read_unlock();
2378 
2379 	return ret;
2380 }
2381 
2382 static void htab_percpu_map_seq_show_elem(struct bpf_map *map, void *key,
2383 					  struct seq_file *m)
2384 {
2385 	struct htab_elem *l;
2386 	void __percpu *pptr;
2387 	int cpu;
2388 
2389 	rcu_read_lock();
2390 
2391 	l = __htab_map_lookup_elem(map, key);
2392 	if (!l) {
2393 		rcu_read_unlock();
2394 		return;
2395 	}
2396 
2397 	btf_type_seq_show(map->btf, map->btf_key_type_id, key, m);
2398 	seq_puts(m, ": {\n");
2399 	pptr = htab_elem_get_ptr(l, map->key_size);
2400 	for_each_possible_cpu(cpu) {
2401 		seq_printf(m, "\tcpu%d: ", cpu);
2402 		btf_type_seq_show(map->btf, map->btf_value_type_id,
2403 				  per_cpu_ptr(pptr, cpu), m);
2404 		seq_puts(m, "\n");
2405 	}
2406 	seq_puts(m, "}\n");
2407 
2408 	rcu_read_unlock();
2409 }
2410 
2411 const struct bpf_map_ops htab_percpu_map_ops = {
2412 	.map_meta_equal = bpf_map_meta_equal,
2413 	.map_alloc_check = htab_map_alloc_check,
2414 	.map_alloc = htab_map_alloc,
2415 	.map_free = htab_map_free,
2416 	.map_get_next_key = htab_map_get_next_key,
2417 	.map_lookup_elem = htab_percpu_map_lookup_elem,
2418 	.map_lookup_and_delete_elem = htab_percpu_map_lookup_and_delete_elem,
2419 	.map_update_elem = htab_percpu_map_update_elem,
2420 	.map_delete_elem = htab_map_delete_elem,
2421 	.map_lookup_percpu_elem = htab_percpu_map_lookup_percpu_elem,
2422 	.map_seq_show_elem = htab_percpu_map_seq_show_elem,
2423 	.map_set_for_each_callback_args = map_set_for_each_callback_args,
2424 	.map_for_each_callback = bpf_for_each_hash_elem,
2425 	.map_mem_usage = htab_map_mem_usage,
2426 	BATCH_OPS(htab_percpu),
2427 	.map_btf_id = &htab_map_btf_ids[0],
2428 	.iter_seq_info = &iter_seq_info,
2429 };
2430 
2431 const struct bpf_map_ops htab_lru_percpu_map_ops = {
2432 	.map_meta_equal = bpf_map_meta_equal,
2433 	.map_alloc_check = htab_map_alloc_check,
2434 	.map_alloc = htab_map_alloc,
2435 	.map_free = htab_map_free,
2436 	.map_get_next_key = htab_map_get_next_key,
2437 	.map_lookup_elem = htab_lru_percpu_map_lookup_elem,
2438 	.map_lookup_and_delete_elem = htab_lru_percpu_map_lookup_and_delete_elem,
2439 	.map_update_elem = htab_lru_percpu_map_update_elem,
2440 	.map_delete_elem = htab_lru_map_delete_elem,
2441 	.map_lookup_percpu_elem = htab_lru_percpu_map_lookup_percpu_elem,
2442 	.map_seq_show_elem = htab_percpu_map_seq_show_elem,
2443 	.map_set_for_each_callback_args = map_set_for_each_callback_args,
2444 	.map_for_each_callback = bpf_for_each_hash_elem,
2445 	.map_mem_usage = htab_map_mem_usage,
2446 	BATCH_OPS(htab_lru_percpu),
2447 	.map_btf_id = &htab_map_btf_ids[0],
2448 	.iter_seq_info = &iter_seq_info,
2449 };
2450 
2451 static int fd_htab_map_alloc_check(union bpf_attr *attr)
2452 {
2453 	if (attr->value_size != sizeof(u32))
2454 		return -EINVAL;
2455 	return htab_map_alloc_check(attr);
2456 }
2457 
2458 static void fd_htab_map_free(struct bpf_map *map)
2459 {
2460 	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2461 	struct hlist_nulls_node *n;
2462 	struct hlist_nulls_head *head;
2463 	struct htab_elem *l;
2464 	int i;
2465 
2466 	for (i = 0; i < htab->n_buckets; i++) {
2467 		head = select_bucket(htab, i);
2468 
2469 		hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
2470 			void *ptr = fd_htab_map_get_ptr(map, l);
2471 
2472 			map->ops->map_fd_put_ptr(ptr);
2473 		}
2474 	}
2475 
2476 	htab_map_free(map);
2477 }
2478 
2479 /* only called from syscall */
2480 int bpf_fd_htab_map_lookup_elem(struct bpf_map *map, void *key, u32 *value)
2481 {
2482 	void **ptr;
2483 	int ret = 0;
2484 
2485 	if (!map->ops->map_fd_sys_lookup_elem)
2486 		return -ENOTSUPP;
2487 
2488 	rcu_read_lock();
2489 	ptr = htab_map_lookup_elem(map, key);
2490 	if (ptr)
2491 		*value = map->ops->map_fd_sys_lookup_elem(READ_ONCE(*ptr));
2492 	else
2493 		ret = -ENOENT;
2494 	rcu_read_unlock();
2495 
2496 	return ret;
2497 }
2498 
2499 /* only called from syscall */
2500 int bpf_fd_htab_map_update_elem(struct bpf_map *map, struct file *map_file,
2501 				void *key, void *value, u64 map_flags)
2502 {
2503 	void *ptr;
2504 	int ret;
2505 	u32 ufd = *(u32 *)value;
2506 
2507 	ptr = map->ops->map_fd_get_ptr(map, map_file, ufd);
2508 	if (IS_ERR(ptr))
2509 		return PTR_ERR(ptr);
2510 
2511 	ret = htab_map_update_elem(map, key, &ptr, map_flags);
2512 	if (ret)
2513 		map->ops->map_fd_put_ptr(ptr);
2514 
2515 	return ret;
2516 }
2517 
2518 static struct bpf_map *htab_of_map_alloc(union bpf_attr *attr)
2519 {
2520 	struct bpf_map *map, *inner_map_meta;
2521 
2522 	inner_map_meta = bpf_map_meta_alloc(attr->inner_map_fd);
2523 	if (IS_ERR(inner_map_meta))
2524 		return inner_map_meta;
2525 
2526 	map = htab_map_alloc(attr);
2527 	if (IS_ERR(map)) {
2528 		bpf_map_meta_free(inner_map_meta);
2529 		return map;
2530 	}
2531 
2532 	map->inner_map_meta = inner_map_meta;
2533 
2534 	return map;
2535 }
2536 
2537 static void *htab_of_map_lookup_elem(struct bpf_map *map, void *key)
2538 {
2539 	struct bpf_map **inner_map  = htab_map_lookup_elem(map, key);
2540 
2541 	if (!inner_map)
2542 		return NULL;
2543 
2544 	return READ_ONCE(*inner_map);
2545 }
2546 
2547 static int htab_of_map_gen_lookup(struct bpf_map *map,
2548 				  struct bpf_insn *insn_buf)
2549 {
2550 	struct bpf_insn *insn = insn_buf;
2551 	const int ret = BPF_REG_0;
2552 
2553 	BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
2554 		     (void *(*)(struct bpf_map *map, void *key))NULL));
2555 	*insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
2556 	*insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 2);
2557 	*insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
2558 				offsetof(struct htab_elem, key) +
2559 				round_up(map->key_size, 8));
2560 	*insn++ = BPF_LDX_MEM(BPF_DW, ret, ret, 0);
2561 
2562 	return insn - insn_buf;
2563 }
2564 
2565 static void htab_of_map_free(struct bpf_map *map)
2566 {
2567 	bpf_map_meta_free(map->inner_map_meta);
2568 	fd_htab_map_free(map);
2569 }
2570 
2571 const struct bpf_map_ops htab_of_maps_map_ops = {
2572 	.map_alloc_check = fd_htab_map_alloc_check,
2573 	.map_alloc = htab_of_map_alloc,
2574 	.map_free = htab_of_map_free,
2575 	.map_get_next_key = htab_map_get_next_key,
2576 	.map_lookup_elem = htab_of_map_lookup_elem,
2577 	.map_delete_elem = htab_map_delete_elem,
2578 	.map_fd_get_ptr = bpf_map_fd_get_ptr,
2579 	.map_fd_put_ptr = bpf_map_fd_put_ptr,
2580 	.map_fd_sys_lookup_elem = bpf_map_fd_sys_lookup_elem,
2581 	.map_gen_lookup = htab_of_map_gen_lookup,
2582 	.map_check_btf = map_check_no_btf,
2583 	.map_mem_usage = htab_map_mem_usage,
2584 	BATCH_OPS(htab),
2585 	.map_btf_id = &htab_map_btf_ids[0],
2586 };
2587