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