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