1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3 * Copyright (c) 2016 Facebook
7 #include <linux/jhash.h>
8 #include <linux/filter.h>
9 #include <linux/rculist_nulls.h>
10 #include <linux/random.h>
11 #include <uapi/linux/btf.h>
12 #include <linux/rcupdate_trace.h>
13 #include "percpu_freelist.h"
14 #include "bpf_lru_list.h"
15 #include "map_in_map.h"
17 #define HTAB_CREATE_FLAG_MASK \
18 (BPF_F_NO_PREALLOC | BPF_F_NO_COMMON_LRU | BPF_F_NUMA_NODE | \
19 BPF_F_ACCESS_MASK | BPF_F_ZERO_SEED)
21 #define BATCH_OPS(_name) \
23 _name##_map_lookup_batch, \
24 .map_lookup_and_delete_batch = \
25 _name##_map_lookup_and_delete_batch, \
27 generic_map_update_batch, \
29 generic_map_delete_batch
32 * The bucket lock has two protection scopes:
34 * 1) Serializing concurrent operations from BPF programs on different
37 * 2) Serializing concurrent operations from BPF programs and sys_bpf()
39 * BPF programs can execute in any context including perf, kprobes and
40 * tracing. As there are almost no limits where perf, kprobes and tracing
41 * can be invoked from the lock operations need to be protected against
42 * deadlocks. Deadlocks can be caused by recursion and by an invocation in
43 * the lock held section when functions which acquire this lock are invoked
44 * from sys_bpf(). BPF recursion is prevented by incrementing the per CPU
45 * variable bpf_prog_active, which prevents BPF programs attached to perf
46 * events, kprobes and tracing to be invoked before the prior invocation
47 * from one of these contexts completed. sys_bpf() uses the same mechanism
48 * by pinning the task to the current CPU and incrementing the recursion
49 * protection across the map operation.
51 * This has subtle implications on PREEMPT_RT. PREEMPT_RT forbids certain
52 * operations like memory allocations (even with GFP_ATOMIC) from atomic
53 * contexts. This is required because even with GFP_ATOMIC the memory
54 * allocator calls into code paths which acquire locks with long held lock
55 * sections. To ensure the deterministic behaviour these locks are regular
56 * spinlocks, which are converted to 'sleepable' spinlocks on RT. The only
57 * true atomic contexts on an RT kernel are the low level hardware
58 * handling, scheduling, low level interrupt handling, NMIs etc. None of
59 * these contexts should ever do memory allocations.
61 * As regular device interrupt handlers and soft interrupts are forced into
62 * thread context, the existing code which does
63 * spin_lock*(); alloc(GPF_ATOMIC); spin_unlock*();
66 * In theory the BPF locks could be converted to regular spinlocks as well,
67 * but the bucket locks and percpu_freelist locks can be taken from
68 * arbitrary contexts (perf, kprobes, tracepoints) which are required to be
69 * atomic contexts even on RT. These mechanisms require preallocated maps,
70 * so there is no need to invoke memory allocations within the lock held
73 * BPF maps which need dynamic allocation are only used from (forced)
74 * thread context on RT and can therefore use regular spinlocks which in
75 * turn allows to invoke memory allocations from the lock held section.
77 * On a non RT kernel this distinction is neither possible nor required.
78 * spinlock maps to raw_spinlock and the extra code is optimized out by the
82 struct hlist_nulls_head head;
84 raw_spinlock_t raw_lock;
89 #define HASHTAB_MAP_LOCK_COUNT 8
90 #define HASHTAB_MAP_LOCK_MASK (HASHTAB_MAP_LOCK_COUNT - 1)
94 struct bucket *buckets;
97 struct pcpu_freelist freelist;
100 struct htab_elem *__percpu *extra_elems;
101 atomic_t count; /* number of elements in this hashtable */
102 u32 n_buckets; /* number of hash buckets */
103 u32 elem_size; /* size of each element in bytes */
105 struct lock_class_key lockdep_key;
106 int __percpu *map_locked[HASHTAB_MAP_LOCK_COUNT];
109 /* each htab element is struct htab_elem + key + value */
112 struct hlist_nulls_node hash_node;
116 struct bpf_htab *htab;
117 struct pcpu_freelist_node fnode;
118 struct htab_elem *batch_flink;
124 struct bpf_lru_node lru_node;
127 char key[] __aligned(8);
130 static inline bool htab_is_prealloc(const struct bpf_htab *htab)
132 return !(htab->map.map_flags & BPF_F_NO_PREALLOC);
135 static inline bool htab_use_raw_lock(const struct bpf_htab *htab)
137 return (!IS_ENABLED(CONFIG_PREEMPT_RT) || htab_is_prealloc(htab));
140 static void htab_init_buckets(struct bpf_htab *htab)
144 for (i = 0; i < htab->n_buckets; i++) {
145 INIT_HLIST_NULLS_HEAD(&htab->buckets[i].head, i);
146 if (htab_use_raw_lock(htab)) {
147 raw_spin_lock_init(&htab->buckets[i].raw_lock);
148 lockdep_set_class(&htab->buckets[i].raw_lock,
151 spin_lock_init(&htab->buckets[i].lock);
152 lockdep_set_class(&htab->buckets[i].lock,
159 static inline int htab_lock_bucket(const struct bpf_htab *htab,
160 struct bucket *b, u32 hash,
161 unsigned long *pflags)
166 hash = hash & min_t(u32, HASHTAB_MAP_LOCK_MASK, htab->n_buckets - 1);
168 use_raw_lock = htab_use_raw_lock(htab);
173 if (unlikely(__this_cpu_inc_return(*(htab->map_locked[hash])) != 1)) {
174 __this_cpu_dec(*(htab->map_locked[hash]));
183 raw_spin_lock_irqsave(&b->raw_lock, flags);
185 spin_lock_irqsave(&b->lock, flags);
191 static inline void htab_unlock_bucket(const struct bpf_htab *htab,
192 struct bucket *b, u32 hash,
195 bool use_raw_lock = htab_use_raw_lock(htab);
197 hash = hash & min_t(u32, HASHTAB_MAP_LOCK_MASK, htab->n_buckets - 1);
199 raw_spin_unlock_irqrestore(&b->raw_lock, flags);
201 spin_unlock_irqrestore(&b->lock, flags);
202 __this_cpu_dec(*(htab->map_locked[hash]));
209 static bool htab_lru_map_delete_node(void *arg, struct bpf_lru_node *node);
211 static bool htab_is_lru(const struct bpf_htab *htab)
213 return htab->map.map_type == BPF_MAP_TYPE_LRU_HASH ||
214 htab->map.map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH;
217 static bool htab_is_percpu(const struct bpf_htab *htab)
219 return htab->map.map_type == BPF_MAP_TYPE_PERCPU_HASH ||
220 htab->map.map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH;
223 static inline void htab_elem_set_ptr(struct htab_elem *l, u32 key_size,
226 *(void __percpu **)(l->key + key_size) = pptr;
229 static inline void __percpu *htab_elem_get_ptr(struct htab_elem *l, u32 key_size)
231 return *(void __percpu **)(l->key + key_size);
234 static void *fd_htab_map_get_ptr(const struct bpf_map *map, struct htab_elem *l)
236 return *(void **)(l->key + roundup(map->key_size, 8));
239 static struct htab_elem *get_htab_elem(struct bpf_htab *htab, int i)
241 return (struct htab_elem *) (htab->elems + i * (u64)htab->elem_size);
244 static bool htab_has_extra_elems(struct bpf_htab *htab)
246 return !htab_is_percpu(htab) && !htab_is_lru(htab);
249 static void htab_free_prealloced_timers(struct bpf_htab *htab)
251 u32 num_entries = htab->map.max_entries;
254 if (likely(!map_value_has_timer(&htab->map)))
256 if (htab_has_extra_elems(htab))
257 num_entries += num_possible_cpus();
259 for (i = 0; i < num_entries; i++) {
260 struct htab_elem *elem;
262 elem = get_htab_elem(htab, i);
263 bpf_timer_cancel_and_free(elem->key +
264 round_up(htab->map.key_size, 8) +
265 htab->map.timer_off);
270 static void htab_free_elems(struct bpf_htab *htab)
274 if (!htab_is_percpu(htab))
277 for (i = 0; i < htab->map.max_entries; i++) {
280 pptr = htab_elem_get_ptr(get_htab_elem(htab, i),
286 bpf_map_area_free(htab->elems);
289 /* The LRU list has a lock (lru_lock). Each htab bucket has a lock
290 * (bucket_lock). If both locks need to be acquired together, the lock
291 * order is always lru_lock -> bucket_lock and this only happens in
292 * bpf_lru_list.c logic. For example, certain code path of
293 * bpf_lru_pop_free(), which is called by function prealloc_lru_pop(),
294 * will acquire lru_lock first followed by acquiring bucket_lock.
296 * In hashtab.c, to avoid deadlock, lock acquisition of
297 * bucket_lock followed by lru_lock is not allowed. In such cases,
298 * bucket_lock needs to be released first before acquiring lru_lock.
300 static struct htab_elem *prealloc_lru_pop(struct bpf_htab *htab, void *key,
303 struct bpf_lru_node *node = bpf_lru_pop_free(&htab->lru, hash);
307 l = container_of(node, struct htab_elem, lru_node);
308 memcpy(l->key, key, htab->map.key_size);
315 static int prealloc_init(struct bpf_htab *htab)
317 u32 num_entries = htab->map.max_entries;
318 int err = -ENOMEM, i;
320 if (htab_has_extra_elems(htab))
321 num_entries += num_possible_cpus();
323 htab->elems = bpf_map_area_alloc((u64)htab->elem_size * num_entries,
324 htab->map.numa_node);
328 if (!htab_is_percpu(htab))
329 goto skip_percpu_elems;
331 for (i = 0; i < num_entries; i++) {
332 u32 size = round_up(htab->map.value_size, 8);
335 pptr = bpf_map_alloc_percpu(&htab->map, size, 8,
336 GFP_USER | __GFP_NOWARN);
339 htab_elem_set_ptr(get_htab_elem(htab, i), htab->map.key_size,
345 if (htab_is_lru(htab))
346 err = bpf_lru_init(&htab->lru,
347 htab->map.map_flags & BPF_F_NO_COMMON_LRU,
348 offsetof(struct htab_elem, hash) -
349 offsetof(struct htab_elem, lru_node),
350 htab_lru_map_delete_node,
353 err = pcpu_freelist_init(&htab->freelist);
358 if (htab_is_lru(htab))
359 bpf_lru_populate(&htab->lru, htab->elems,
360 offsetof(struct htab_elem, lru_node),
361 htab->elem_size, num_entries);
363 pcpu_freelist_populate(&htab->freelist,
364 htab->elems + offsetof(struct htab_elem, fnode),
365 htab->elem_size, num_entries);
370 htab_free_elems(htab);
374 static void prealloc_destroy(struct bpf_htab *htab)
376 htab_free_elems(htab);
378 if (htab_is_lru(htab))
379 bpf_lru_destroy(&htab->lru);
381 pcpu_freelist_destroy(&htab->freelist);
384 static int alloc_extra_elems(struct bpf_htab *htab)
386 struct htab_elem *__percpu *pptr, *l_new;
387 struct pcpu_freelist_node *l;
390 pptr = bpf_map_alloc_percpu(&htab->map, sizeof(struct htab_elem *), 8,
391 GFP_USER | __GFP_NOWARN);
395 for_each_possible_cpu(cpu) {
396 l = pcpu_freelist_pop(&htab->freelist);
397 /* pop will succeed, since prealloc_init()
398 * preallocated extra num_possible_cpus elements
400 l_new = container_of(l, struct htab_elem, fnode);
401 *per_cpu_ptr(pptr, cpu) = l_new;
403 htab->extra_elems = pptr;
407 /* Called from syscall */
408 static int htab_map_alloc_check(union bpf_attr *attr)
410 bool percpu = (attr->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
411 attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);
412 bool lru = (attr->map_type == BPF_MAP_TYPE_LRU_HASH ||
413 attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);
414 /* percpu_lru means each cpu has its own LRU list.
415 * it is different from BPF_MAP_TYPE_PERCPU_HASH where
416 * the map's value itself is percpu. percpu_lru has
417 * nothing to do with the map's value.
419 bool percpu_lru = (attr->map_flags & BPF_F_NO_COMMON_LRU);
420 bool prealloc = !(attr->map_flags & BPF_F_NO_PREALLOC);
421 bool zero_seed = (attr->map_flags & BPF_F_ZERO_SEED);
422 int numa_node = bpf_map_attr_numa_node(attr);
424 BUILD_BUG_ON(offsetof(struct htab_elem, htab) !=
425 offsetof(struct htab_elem, hash_node.pprev));
426 BUILD_BUG_ON(offsetof(struct htab_elem, fnode.next) !=
427 offsetof(struct htab_elem, hash_node.pprev));
429 if (lru && !bpf_capable())
430 /* LRU implementation is much complicated than other
431 * maps. Hence, limit to CAP_BPF.
435 if (zero_seed && !capable(CAP_SYS_ADMIN))
436 /* Guard against local DoS, and discourage production use. */
439 if (attr->map_flags & ~HTAB_CREATE_FLAG_MASK ||
440 !bpf_map_flags_access_ok(attr->map_flags))
443 if (!lru && percpu_lru)
446 if (lru && !prealloc)
449 if (numa_node != NUMA_NO_NODE && (percpu || percpu_lru))
452 /* check sanity of attributes.
453 * value_size == 0 may be allowed in the future to use map as a set
455 if (attr->max_entries == 0 || attr->key_size == 0 ||
456 attr->value_size == 0)
459 if ((u64)attr->key_size + attr->value_size >= KMALLOC_MAX_SIZE -
460 sizeof(struct htab_elem))
461 /* if key_size + value_size is bigger, the user space won't be
462 * able to access the elements via bpf syscall. This check
463 * also makes sure that the elem_size doesn't overflow and it's
464 * kmalloc-able later in htab_map_update_elem()
471 static struct bpf_map *htab_map_alloc(union bpf_attr *attr)
473 bool percpu = (attr->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
474 attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);
475 bool lru = (attr->map_type == BPF_MAP_TYPE_LRU_HASH ||
476 attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);
477 /* percpu_lru means each cpu has its own LRU list.
478 * it is different from BPF_MAP_TYPE_PERCPU_HASH where
479 * the map's value itself is percpu. percpu_lru has
480 * nothing to do with the map's value.
482 bool percpu_lru = (attr->map_flags & BPF_F_NO_COMMON_LRU);
483 bool prealloc = !(attr->map_flags & BPF_F_NO_PREALLOC);
484 struct bpf_htab *htab;
487 htab = kzalloc(sizeof(*htab), GFP_USER | __GFP_ACCOUNT);
489 return ERR_PTR(-ENOMEM);
491 lockdep_register_key(&htab->lockdep_key);
493 bpf_map_init_from_attr(&htab->map, attr);
496 /* ensure each CPU's lru list has >=1 elements.
497 * since we are at it, make each lru list has the same
498 * number of elements.
500 htab->map.max_entries = roundup(attr->max_entries,
501 num_possible_cpus());
502 if (htab->map.max_entries < attr->max_entries)
503 htab->map.max_entries = rounddown(attr->max_entries,
504 num_possible_cpus());
507 /* hash table size must be power of 2 */
508 htab->n_buckets = roundup_pow_of_two(htab->map.max_entries);
510 htab->elem_size = sizeof(struct htab_elem) +
511 round_up(htab->map.key_size, 8);
513 htab->elem_size += sizeof(void *);
515 htab->elem_size += round_up(htab->map.value_size, 8);
518 /* prevent zero size kmalloc and check for u32 overflow */
519 if (htab->n_buckets == 0 ||
520 htab->n_buckets > U32_MAX / sizeof(struct bucket))
524 htab->buckets = bpf_map_area_alloc(htab->n_buckets *
525 sizeof(struct bucket),
526 htab->map.numa_node);
530 for (i = 0; i < HASHTAB_MAP_LOCK_COUNT; i++) {
531 htab->map_locked[i] = bpf_map_alloc_percpu(&htab->map,
535 if (!htab->map_locked[i])
536 goto free_map_locked;
539 if (htab->map.map_flags & BPF_F_ZERO_SEED)
542 htab->hashrnd = get_random_int();
544 htab_init_buckets(htab);
547 err = prealloc_init(htab);
549 goto free_map_locked;
551 if (!percpu && !lru) {
552 /* lru itself can remove the least used element, so
553 * there is no need for an extra elem during map_update.
555 err = alloc_extra_elems(htab);
564 prealloc_destroy(htab);
566 for (i = 0; i < HASHTAB_MAP_LOCK_COUNT; i++)
567 free_percpu(htab->map_locked[i]);
568 bpf_map_area_free(htab->buckets);
570 lockdep_unregister_key(&htab->lockdep_key);
575 static inline u32 htab_map_hash(const void *key, u32 key_len, u32 hashrnd)
577 return jhash(key, key_len, hashrnd);
580 static inline struct bucket *__select_bucket(struct bpf_htab *htab, u32 hash)
582 return &htab->buckets[hash & (htab->n_buckets - 1)];
585 static inline struct hlist_nulls_head *select_bucket(struct bpf_htab *htab, u32 hash)
587 return &__select_bucket(htab, hash)->head;
590 /* this lookup function can only be called with bucket lock taken */
591 static struct htab_elem *lookup_elem_raw(struct hlist_nulls_head *head, u32 hash,
592 void *key, u32 key_size)
594 struct hlist_nulls_node *n;
597 hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
598 if (l->hash == hash && !memcmp(&l->key, key, key_size))
604 /* can be called without bucket lock. it will repeat the loop in
605 * the unlikely event when elements moved from one bucket into another
606 * while link list is being walked
608 static struct htab_elem *lookup_nulls_elem_raw(struct hlist_nulls_head *head,
610 u32 key_size, u32 n_buckets)
612 struct hlist_nulls_node *n;
616 hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
617 if (l->hash == hash && !memcmp(&l->key, key, key_size))
620 if (unlikely(get_nulls_value(n) != (hash & (n_buckets - 1))))
626 /* Called from syscall or from eBPF program directly, so
627 * arguments have to match bpf_map_lookup_elem() exactly.
628 * The return value is adjusted by BPF instructions
629 * in htab_map_gen_lookup().
631 static void *__htab_map_lookup_elem(struct bpf_map *map, void *key)
633 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
634 struct hlist_nulls_head *head;
638 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
639 !rcu_read_lock_bh_held());
641 key_size = map->key_size;
643 hash = htab_map_hash(key, key_size, htab->hashrnd);
645 head = select_bucket(htab, hash);
647 l = lookup_nulls_elem_raw(head, hash, key, key_size, htab->n_buckets);
652 static void *htab_map_lookup_elem(struct bpf_map *map, void *key)
654 struct htab_elem *l = __htab_map_lookup_elem(map, key);
657 return l->key + round_up(map->key_size, 8);
662 /* inline bpf_map_lookup_elem() call.
665 * bpf_map_lookup_elem
666 * map->ops->map_lookup_elem
667 * htab_map_lookup_elem
668 * __htab_map_lookup_elem
671 * __htab_map_lookup_elem
673 static int htab_map_gen_lookup(struct bpf_map *map, struct bpf_insn *insn_buf)
675 struct bpf_insn *insn = insn_buf;
676 const int ret = BPF_REG_0;
678 BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
679 (void *(*)(struct bpf_map *map, void *key))NULL));
680 *insn++ = BPF_EMIT_CALL(BPF_CAST_CALL(__htab_map_lookup_elem));
681 *insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 1);
682 *insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
683 offsetof(struct htab_elem, key) +
684 round_up(map->key_size, 8));
685 return insn - insn_buf;
688 static __always_inline void *__htab_lru_map_lookup_elem(struct bpf_map *map,
689 void *key, const bool mark)
691 struct htab_elem *l = __htab_map_lookup_elem(map, key);
695 bpf_lru_node_set_ref(&l->lru_node);
696 return l->key + round_up(map->key_size, 8);
702 static void *htab_lru_map_lookup_elem(struct bpf_map *map, void *key)
704 return __htab_lru_map_lookup_elem(map, key, true);
707 static void *htab_lru_map_lookup_elem_sys(struct bpf_map *map, void *key)
709 return __htab_lru_map_lookup_elem(map, key, false);
712 static int htab_lru_map_gen_lookup(struct bpf_map *map,
713 struct bpf_insn *insn_buf)
715 struct bpf_insn *insn = insn_buf;
716 const int ret = BPF_REG_0;
717 const int ref_reg = BPF_REG_1;
719 BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
720 (void *(*)(struct bpf_map *map, void *key))NULL));
721 *insn++ = BPF_EMIT_CALL(BPF_CAST_CALL(__htab_map_lookup_elem));
722 *insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 4);
723 *insn++ = BPF_LDX_MEM(BPF_B, ref_reg, ret,
724 offsetof(struct htab_elem, lru_node) +
725 offsetof(struct bpf_lru_node, ref));
726 *insn++ = BPF_JMP_IMM(BPF_JNE, ref_reg, 0, 1);
727 *insn++ = BPF_ST_MEM(BPF_B, ret,
728 offsetof(struct htab_elem, lru_node) +
729 offsetof(struct bpf_lru_node, ref),
731 *insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
732 offsetof(struct htab_elem, key) +
733 round_up(map->key_size, 8));
734 return insn - insn_buf;
737 static void check_and_free_timer(struct bpf_htab *htab, struct htab_elem *elem)
739 if (unlikely(map_value_has_timer(&htab->map)))
740 bpf_timer_cancel_and_free(elem->key +
741 round_up(htab->map.key_size, 8) +
742 htab->map.timer_off);
745 /* It is called from the bpf_lru_list when the LRU needs to delete
746 * older elements from the htab.
748 static bool htab_lru_map_delete_node(void *arg, struct bpf_lru_node *node)
750 struct bpf_htab *htab = (struct bpf_htab *)arg;
751 struct htab_elem *l = NULL, *tgt_l;
752 struct hlist_nulls_head *head;
753 struct hlist_nulls_node *n;
758 tgt_l = container_of(node, struct htab_elem, lru_node);
759 b = __select_bucket(htab, tgt_l->hash);
762 ret = htab_lock_bucket(htab, b, tgt_l->hash, &flags);
766 hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
768 hlist_nulls_del_rcu(&l->hash_node);
769 check_and_free_timer(htab, l);
773 htab_unlock_bucket(htab, b, tgt_l->hash, flags);
778 /* Called from syscall */
779 static int htab_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
781 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
782 struct hlist_nulls_head *head;
783 struct htab_elem *l, *next_l;
787 WARN_ON_ONCE(!rcu_read_lock_held());
789 key_size = map->key_size;
792 goto find_first_elem;
794 hash = htab_map_hash(key, key_size, htab->hashrnd);
796 head = select_bucket(htab, hash);
799 l = lookup_nulls_elem_raw(head, hash, key, key_size, htab->n_buckets);
802 goto find_first_elem;
804 /* key was found, get next key in the same bucket */
805 next_l = hlist_nulls_entry_safe(rcu_dereference_raw(hlist_nulls_next_rcu(&l->hash_node)),
806 struct htab_elem, hash_node);
809 /* if next elem in this hash list is non-zero, just return it */
810 memcpy(next_key, next_l->key, key_size);
814 /* no more elements in this hash list, go to the next bucket */
815 i = hash & (htab->n_buckets - 1);
819 /* iterate over buckets */
820 for (; i < htab->n_buckets; i++) {
821 head = select_bucket(htab, i);
823 /* pick first element in the bucket */
824 next_l = hlist_nulls_entry_safe(rcu_dereference_raw(hlist_nulls_first_rcu(head)),
825 struct htab_elem, hash_node);
827 /* if it's not empty, just return it */
828 memcpy(next_key, next_l->key, key_size);
833 /* iterated over all buckets and all elements */
837 static void htab_elem_free(struct bpf_htab *htab, struct htab_elem *l)
839 if (htab->map.map_type == BPF_MAP_TYPE_PERCPU_HASH)
840 free_percpu(htab_elem_get_ptr(l, htab->map.key_size));
841 check_and_free_timer(htab, l);
845 static void htab_elem_free_rcu(struct rcu_head *head)
847 struct htab_elem *l = container_of(head, struct htab_elem, rcu);
848 struct bpf_htab *htab = l->htab;
850 htab_elem_free(htab, l);
853 static void htab_put_fd_value(struct bpf_htab *htab, struct htab_elem *l)
855 struct bpf_map *map = &htab->map;
858 if (map->ops->map_fd_put_ptr) {
859 ptr = fd_htab_map_get_ptr(map, l);
860 map->ops->map_fd_put_ptr(ptr);
864 static void free_htab_elem(struct bpf_htab *htab, struct htab_elem *l)
866 htab_put_fd_value(htab, l);
868 if (htab_is_prealloc(htab)) {
869 check_and_free_timer(htab, l);
870 __pcpu_freelist_push(&htab->freelist, &l->fnode);
872 atomic_dec(&htab->count);
874 call_rcu(&l->rcu, htab_elem_free_rcu);
878 static void pcpu_copy_value(struct bpf_htab *htab, void __percpu *pptr,
879 void *value, bool onallcpus)
882 /* copy true value_size bytes */
883 memcpy(this_cpu_ptr(pptr), value, htab->map.value_size);
885 u32 size = round_up(htab->map.value_size, 8);
888 for_each_possible_cpu(cpu) {
889 bpf_long_memcpy(per_cpu_ptr(pptr, cpu),
896 static void pcpu_init_value(struct bpf_htab *htab, void __percpu *pptr,
897 void *value, bool onallcpus)
899 /* When using prealloc and not setting the initial value on all cpus,
900 * zero-fill element values for other cpus (just as what happens when
901 * not using prealloc). Otherwise, bpf program has no way to ensure
902 * known initial values for cpus other than current one
903 * (onallcpus=false always when coming from bpf prog).
905 if (htab_is_prealloc(htab) && !onallcpus) {
906 u32 size = round_up(htab->map.value_size, 8);
907 int current_cpu = raw_smp_processor_id();
910 for_each_possible_cpu(cpu) {
911 if (cpu == current_cpu)
912 bpf_long_memcpy(per_cpu_ptr(pptr, cpu), value,
915 memset(per_cpu_ptr(pptr, cpu), 0, size);
918 pcpu_copy_value(htab, pptr, value, onallcpus);
922 static bool fd_htab_map_needs_adjust(const struct bpf_htab *htab)
924 return htab->map.map_type == BPF_MAP_TYPE_HASH_OF_MAPS &&
928 static struct htab_elem *alloc_htab_elem(struct bpf_htab *htab, void *key,
929 void *value, u32 key_size, u32 hash,
930 bool percpu, bool onallcpus,
931 struct htab_elem *old_elem)
933 u32 size = htab->map.value_size;
934 bool prealloc = htab_is_prealloc(htab);
935 struct htab_elem *l_new, **pl_new;
940 /* if we're updating the existing element,
941 * use per-cpu extra elems to avoid freelist_pop/push
943 pl_new = this_cpu_ptr(htab->extra_elems);
945 htab_put_fd_value(htab, old_elem);
948 struct pcpu_freelist_node *l;
950 l = __pcpu_freelist_pop(&htab->freelist);
952 return ERR_PTR(-E2BIG);
953 l_new = container_of(l, struct htab_elem, fnode);
956 if (atomic_inc_return(&htab->count) > htab->map.max_entries)
958 /* when map is full and update() is replacing
959 * old element, it's ok to allocate, since
960 * old element will be freed immediately.
961 * Otherwise return an error
963 l_new = ERR_PTR(-E2BIG);
966 l_new = bpf_map_kmalloc_node(&htab->map, htab->elem_size,
967 GFP_ATOMIC | __GFP_NOWARN,
968 htab->map.numa_node);
970 l_new = ERR_PTR(-ENOMEM);
973 check_and_init_map_value(&htab->map,
974 l_new->key + round_up(key_size, 8));
977 memcpy(l_new->key, key, key_size);
979 size = round_up(size, 8);
981 pptr = htab_elem_get_ptr(l_new, key_size);
983 /* alloc_percpu zero-fills */
984 pptr = bpf_map_alloc_percpu(&htab->map, size, 8,
985 GFP_ATOMIC | __GFP_NOWARN);
988 l_new = ERR_PTR(-ENOMEM);
993 pcpu_init_value(htab, pptr, value, onallcpus);
996 htab_elem_set_ptr(l_new, key_size, pptr);
997 } else if (fd_htab_map_needs_adjust(htab)) {
998 size = round_up(size, 8);
999 memcpy(l_new->key + round_up(key_size, 8), value, size);
1001 copy_map_value(&htab->map,
1002 l_new->key + round_up(key_size, 8),
1009 atomic_dec(&htab->count);
1013 static int check_flags(struct bpf_htab *htab, struct htab_elem *l_old,
1016 if (l_old && (map_flags & ~BPF_F_LOCK) == BPF_NOEXIST)
1017 /* elem already exists */
1020 if (!l_old && (map_flags & ~BPF_F_LOCK) == BPF_EXIST)
1021 /* elem doesn't exist, cannot update it */
1027 /* Called from syscall or from eBPF program */
1028 static int htab_map_update_elem(struct bpf_map *map, void *key, void *value,
1031 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1032 struct htab_elem *l_new = NULL, *l_old;
1033 struct hlist_nulls_head *head;
1034 unsigned long flags;
1039 if (unlikely((map_flags & ~BPF_F_LOCK) > BPF_EXIST))
1043 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1044 !rcu_read_lock_bh_held());
1046 key_size = map->key_size;
1048 hash = htab_map_hash(key, key_size, htab->hashrnd);
1050 b = __select_bucket(htab, hash);
1053 if (unlikely(map_flags & BPF_F_LOCK)) {
1054 if (unlikely(!map_value_has_spin_lock(map)))
1056 /* find an element without taking the bucket lock */
1057 l_old = lookup_nulls_elem_raw(head, hash, key, key_size,
1059 ret = check_flags(htab, l_old, map_flags);
1063 /* grab the element lock and update value in place */
1064 copy_map_value_locked(map,
1065 l_old->key + round_up(key_size, 8),
1069 /* fall through, grab the bucket lock and lookup again.
1070 * 99.9% chance that the element won't be found,
1071 * but second lookup under lock has to be done.
1075 ret = htab_lock_bucket(htab, b, hash, &flags);
1079 l_old = lookup_elem_raw(head, hash, key, key_size);
1081 ret = check_flags(htab, l_old, map_flags);
1085 if (unlikely(l_old && (map_flags & BPF_F_LOCK))) {
1086 /* first lookup without the bucket lock didn't find the element,
1087 * but second lookup with the bucket lock found it.
1088 * This case is highly unlikely, but has to be dealt with:
1089 * grab the element lock in addition to the bucket lock
1090 * and update element in place
1092 copy_map_value_locked(map,
1093 l_old->key + round_up(key_size, 8),
1099 l_new = alloc_htab_elem(htab, key, value, key_size, hash, false, false,
1101 if (IS_ERR(l_new)) {
1102 /* all pre-allocated elements are in use or memory exhausted */
1103 ret = PTR_ERR(l_new);
1107 /* add new element to the head of the list, so that
1108 * concurrent search will find it before old elem
1110 hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1112 hlist_nulls_del_rcu(&l_old->hash_node);
1113 if (!htab_is_prealloc(htab))
1114 free_htab_elem(htab, l_old);
1116 check_and_free_timer(htab, l_old);
1120 htab_unlock_bucket(htab, b, hash, flags);
1124 static void htab_lru_push_free(struct bpf_htab *htab, struct htab_elem *elem)
1126 check_and_free_timer(htab, elem);
1127 bpf_lru_push_free(&htab->lru, &elem->lru_node);
1130 static int htab_lru_map_update_elem(struct bpf_map *map, void *key, void *value,
1133 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1134 struct htab_elem *l_new, *l_old = NULL;
1135 struct hlist_nulls_head *head;
1136 unsigned long flags;
1141 if (unlikely(map_flags > BPF_EXIST))
1145 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1146 !rcu_read_lock_bh_held());
1148 key_size = map->key_size;
1150 hash = htab_map_hash(key, key_size, htab->hashrnd);
1152 b = __select_bucket(htab, hash);
1155 /* For LRU, we need to alloc before taking bucket's
1156 * spinlock because getting free nodes from LRU may need
1157 * to remove older elements from htab and this removal
1158 * operation will need a bucket lock.
1160 l_new = prealloc_lru_pop(htab, key, hash);
1163 copy_map_value(&htab->map,
1164 l_new->key + round_up(map->key_size, 8), value);
1166 ret = htab_lock_bucket(htab, b, hash, &flags);
1168 goto err_lock_bucket;
1170 l_old = lookup_elem_raw(head, hash, key, key_size);
1172 ret = check_flags(htab, l_old, map_flags);
1176 /* add new element to the head of the list, so that
1177 * concurrent search will find it before old elem
1179 hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1181 bpf_lru_node_set_ref(&l_new->lru_node);
1182 hlist_nulls_del_rcu(&l_old->hash_node);
1187 htab_unlock_bucket(htab, b, hash, flags);
1191 htab_lru_push_free(htab, l_new);
1193 htab_lru_push_free(htab, l_old);
1198 static int __htab_percpu_map_update_elem(struct bpf_map *map, void *key,
1199 void *value, u64 map_flags,
1202 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1203 struct htab_elem *l_new = NULL, *l_old;
1204 struct hlist_nulls_head *head;
1205 unsigned long flags;
1210 if (unlikely(map_flags > BPF_EXIST))
1214 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1215 !rcu_read_lock_bh_held());
1217 key_size = map->key_size;
1219 hash = htab_map_hash(key, key_size, htab->hashrnd);
1221 b = __select_bucket(htab, hash);
1224 ret = htab_lock_bucket(htab, b, hash, &flags);
1228 l_old = lookup_elem_raw(head, hash, key, key_size);
1230 ret = check_flags(htab, l_old, map_flags);
1235 /* per-cpu hash map can update value in-place */
1236 pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size),
1239 l_new = alloc_htab_elem(htab, key, value, key_size,
1240 hash, true, onallcpus, NULL);
1241 if (IS_ERR(l_new)) {
1242 ret = PTR_ERR(l_new);
1245 hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1249 htab_unlock_bucket(htab, b, hash, flags);
1253 static int __htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key,
1254 void *value, u64 map_flags,
1257 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1258 struct htab_elem *l_new = NULL, *l_old;
1259 struct hlist_nulls_head *head;
1260 unsigned long flags;
1265 if (unlikely(map_flags > BPF_EXIST))
1269 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1270 !rcu_read_lock_bh_held());
1272 key_size = map->key_size;
1274 hash = htab_map_hash(key, key_size, htab->hashrnd);
1276 b = __select_bucket(htab, hash);
1279 /* For LRU, we need to alloc before taking bucket's
1280 * spinlock because LRU's elem alloc may need
1281 * to remove older elem from htab and this removal
1282 * operation will need a bucket lock.
1284 if (map_flags != BPF_EXIST) {
1285 l_new = prealloc_lru_pop(htab, key, hash);
1290 ret = htab_lock_bucket(htab, b, hash, &flags);
1292 goto err_lock_bucket;
1294 l_old = lookup_elem_raw(head, hash, key, key_size);
1296 ret = check_flags(htab, l_old, map_flags);
1301 bpf_lru_node_set_ref(&l_old->lru_node);
1303 /* per-cpu hash map can update value in-place */
1304 pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size),
1307 pcpu_init_value(htab, htab_elem_get_ptr(l_new, key_size),
1309 hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1314 htab_unlock_bucket(htab, b, hash, flags);
1317 bpf_lru_push_free(&htab->lru, &l_new->lru_node);
1321 static int htab_percpu_map_update_elem(struct bpf_map *map, void *key,
1322 void *value, u64 map_flags)
1324 return __htab_percpu_map_update_elem(map, key, value, map_flags, false);
1327 static int htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key,
1328 void *value, u64 map_flags)
1330 return __htab_lru_percpu_map_update_elem(map, key, value, map_flags,
1334 /* Called from syscall or from eBPF program */
1335 static int htab_map_delete_elem(struct bpf_map *map, void *key)
1337 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1338 struct hlist_nulls_head *head;
1340 struct htab_elem *l;
1341 unsigned long flags;
1345 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1346 !rcu_read_lock_bh_held());
1348 key_size = map->key_size;
1350 hash = htab_map_hash(key, key_size, htab->hashrnd);
1351 b = __select_bucket(htab, hash);
1354 ret = htab_lock_bucket(htab, b, hash, &flags);
1358 l = lookup_elem_raw(head, hash, key, key_size);
1361 hlist_nulls_del_rcu(&l->hash_node);
1362 free_htab_elem(htab, l);
1367 htab_unlock_bucket(htab, b, hash, flags);
1371 static int htab_lru_map_delete_elem(struct bpf_map *map, void *key)
1373 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1374 struct hlist_nulls_head *head;
1376 struct htab_elem *l;
1377 unsigned long flags;
1381 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1382 !rcu_read_lock_bh_held());
1384 key_size = map->key_size;
1386 hash = htab_map_hash(key, key_size, htab->hashrnd);
1387 b = __select_bucket(htab, hash);
1390 ret = htab_lock_bucket(htab, b, hash, &flags);
1394 l = lookup_elem_raw(head, hash, key, key_size);
1397 hlist_nulls_del_rcu(&l->hash_node);
1401 htab_unlock_bucket(htab, b, hash, flags);
1403 htab_lru_push_free(htab, l);
1407 static void delete_all_elements(struct bpf_htab *htab)
1411 for (i = 0; i < htab->n_buckets; i++) {
1412 struct hlist_nulls_head *head = select_bucket(htab, i);
1413 struct hlist_nulls_node *n;
1414 struct htab_elem *l;
1416 hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
1417 hlist_nulls_del_rcu(&l->hash_node);
1418 htab_elem_free(htab, l);
1423 static void htab_free_malloced_timers(struct bpf_htab *htab)
1428 for (i = 0; i < htab->n_buckets; i++) {
1429 struct hlist_nulls_head *head = select_bucket(htab, i);
1430 struct hlist_nulls_node *n;
1431 struct htab_elem *l;
1433 hlist_nulls_for_each_entry(l, n, head, hash_node)
1434 check_and_free_timer(htab, l);
1440 static void htab_map_free_timers(struct bpf_map *map)
1442 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1444 if (likely(!map_value_has_timer(&htab->map)))
1446 if (!htab_is_prealloc(htab))
1447 htab_free_malloced_timers(htab);
1449 htab_free_prealloced_timers(htab);
1452 /* Called when map->refcnt goes to zero, either from workqueue or from syscall */
1453 static void htab_map_free(struct bpf_map *map)
1455 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1458 /* bpf_free_used_maps() or close(map_fd) will trigger this map_free callback.
1459 * bpf_free_used_maps() is called after bpf prog is no longer executing.
1460 * There is no need to synchronize_rcu() here to protect map elements.
1463 /* some of free_htab_elem() callbacks for elements of this map may
1464 * not have executed. Wait for them.
1467 if (!htab_is_prealloc(htab))
1468 delete_all_elements(htab);
1470 prealloc_destroy(htab);
1472 free_percpu(htab->extra_elems);
1473 bpf_map_area_free(htab->buckets);
1474 for (i = 0; i < HASHTAB_MAP_LOCK_COUNT; i++)
1475 free_percpu(htab->map_locked[i]);
1476 lockdep_unregister_key(&htab->lockdep_key);
1480 static void htab_map_seq_show_elem(struct bpf_map *map, void *key,
1487 value = htab_map_lookup_elem(map, key);
1493 btf_type_seq_show(map->btf, map->btf_key_type_id, key, m);
1495 btf_type_seq_show(map->btf, map->btf_value_type_id, value, m);
1501 static int __htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
1502 void *value, bool is_lru_map,
1503 bool is_percpu, u64 flags)
1505 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1506 struct hlist_nulls_head *head;
1507 unsigned long bflags;
1508 struct htab_elem *l;
1513 key_size = map->key_size;
1515 hash = htab_map_hash(key, key_size, htab->hashrnd);
1516 b = __select_bucket(htab, hash);
1519 ret = htab_lock_bucket(htab, b, hash, &bflags);
1523 l = lookup_elem_raw(head, hash, key, key_size);
1528 u32 roundup_value_size = round_up(map->value_size, 8);
1529 void __percpu *pptr;
1532 pptr = htab_elem_get_ptr(l, key_size);
1533 for_each_possible_cpu(cpu) {
1534 bpf_long_memcpy(value + off,
1535 per_cpu_ptr(pptr, cpu),
1536 roundup_value_size);
1537 off += roundup_value_size;
1540 u32 roundup_key_size = round_up(map->key_size, 8);
1542 if (flags & BPF_F_LOCK)
1543 copy_map_value_locked(map, value, l->key +
1547 copy_map_value(map, value, l->key +
1549 check_and_init_map_value(map, value);
1552 hlist_nulls_del_rcu(&l->hash_node);
1554 free_htab_elem(htab, l);
1557 htab_unlock_bucket(htab, b, hash, bflags);
1559 if (is_lru_map && l)
1560 htab_lru_push_free(htab, l);
1565 static int htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
1566 void *value, u64 flags)
1568 return __htab_map_lookup_and_delete_elem(map, key, value, false, false,
1572 static int htab_percpu_map_lookup_and_delete_elem(struct bpf_map *map,
1573 void *key, void *value,
1576 return __htab_map_lookup_and_delete_elem(map, key, value, false, true,
1580 static int htab_lru_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
1581 void *value, u64 flags)
1583 return __htab_map_lookup_and_delete_elem(map, key, value, true, false,
1587 static int htab_lru_percpu_map_lookup_and_delete_elem(struct bpf_map *map,
1588 void *key, void *value,
1591 return __htab_map_lookup_and_delete_elem(map, key, value, true, true,
1596 __htab_map_lookup_and_delete_batch(struct bpf_map *map,
1597 const union bpf_attr *attr,
1598 union bpf_attr __user *uattr,
1599 bool do_delete, bool is_lru_map,
1602 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1603 u32 bucket_cnt, total, key_size, value_size, roundup_key_size;
1604 void *keys = NULL, *values = NULL, *value, *dst_key, *dst_val;
1605 void __user *uvalues = u64_to_user_ptr(attr->batch.values);
1606 void __user *ukeys = u64_to_user_ptr(attr->batch.keys);
1607 void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1608 u32 batch, max_count, size, bucket_size;
1609 struct htab_elem *node_to_free = NULL;
1610 u64 elem_map_flags, map_flags;
1611 struct hlist_nulls_head *head;
1612 struct hlist_nulls_node *n;
1613 unsigned long flags = 0;
1614 bool locked = false;
1615 struct htab_elem *l;
1619 elem_map_flags = attr->batch.elem_flags;
1620 if ((elem_map_flags & ~BPF_F_LOCK) ||
1621 ((elem_map_flags & BPF_F_LOCK) && !map_value_has_spin_lock(map)))
1624 map_flags = attr->batch.flags;
1628 max_count = attr->batch.count;
1632 if (put_user(0, &uattr->batch.count))
1636 if (ubatch && copy_from_user(&batch, ubatch, sizeof(batch)))
1639 if (batch >= htab->n_buckets)
1642 key_size = htab->map.key_size;
1643 roundup_key_size = round_up(htab->map.key_size, 8);
1644 value_size = htab->map.value_size;
1645 size = round_up(value_size, 8);
1647 value_size = size * num_possible_cpus();
1649 /* while experimenting with hash tables with sizes ranging from 10 to
1650 * 1000, it was observed that a bucket can have upto 5 entries.
1655 /* We cannot do copy_from_user or copy_to_user inside
1656 * the rcu_read_lock. Allocate enough space here.
1658 keys = kvmalloc_array(key_size, bucket_size, GFP_USER | __GFP_NOWARN);
1659 values = kvmalloc_array(value_size, bucket_size, GFP_USER | __GFP_NOWARN);
1660 if (!keys || !values) {
1666 bpf_disable_instrumentation();
1671 b = &htab->buckets[batch];
1673 /* do not grab the lock unless need it (bucket_cnt > 0). */
1675 ret = htab_lock_bucket(htab, b, batch, &flags);
1678 bpf_enable_instrumentation();
1684 hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
1687 if (bucket_cnt && !locked) {
1692 if (bucket_cnt > (max_count - total)) {
1695 /* Note that since bucket_cnt > 0 here, it is implicit
1696 * that the locked was grabbed, so release it.
1698 htab_unlock_bucket(htab, b, batch, flags);
1700 bpf_enable_instrumentation();
1704 if (bucket_cnt > bucket_size) {
1705 bucket_size = bucket_cnt;
1706 /* Note that since bucket_cnt > 0 here, it is implicit
1707 * that the locked was grabbed, so release it.
1709 htab_unlock_bucket(htab, b, batch, flags);
1711 bpf_enable_instrumentation();
1717 /* Next block is only safe to run if you have grabbed the lock */
1721 hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
1722 memcpy(dst_key, l->key, key_size);
1726 void __percpu *pptr;
1728 pptr = htab_elem_get_ptr(l, map->key_size);
1729 for_each_possible_cpu(cpu) {
1730 bpf_long_memcpy(dst_val + off,
1731 per_cpu_ptr(pptr, cpu), size);
1735 value = l->key + roundup_key_size;
1736 if (elem_map_flags & BPF_F_LOCK)
1737 copy_map_value_locked(map, dst_val, value,
1740 copy_map_value(map, dst_val, value);
1741 check_and_init_map_value(map, dst_val);
1744 hlist_nulls_del_rcu(&l->hash_node);
1746 /* bpf_lru_push_free() will acquire lru_lock, which
1747 * may cause deadlock. See comments in function
1748 * prealloc_lru_pop(). Let us do bpf_lru_push_free()
1749 * after releasing the bucket lock.
1752 l->batch_flink = node_to_free;
1755 free_htab_elem(htab, l);
1758 dst_key += key_size;
1759 dst_val += value_size;
1762 htab_unlock_bucket(htab, b, batch, flags);
1765 while (node_to_free) {
1767 node_to_free = node_to_free->batch_flink;
1768 htab_lru_push_free(htab, l);
1772 /* If we are not copying data, we can go to next bucket and avoid
1773 * unlocking the rcu.
1775 if (!bucket_cnt && (batch + 1 < htab->n_buckets)) {
1781 bpf_enable_instrumentation();
1782 if (bucket_cnt && (copy_to_user(ukeys + total * key_size, keys,
1783 key_size * bucket_cnt) ||
1784 copy_to_user(uvalues + total * value_size, values,
1785 value_size * bucket_cnt))) {
1790 total += bucket_cnt;
1792 if (batch >= htab->n_buckets) {
1802 /* copy # of entries and next batch */
1803 ubatch = u64_to_user_ptr(attr->batch.out_batch);
1804 if (copy_to_user(ubatch, &batch, sizeof(batch)) ||
1805 put_user(total, &uattr->batch.count))
1815 htab_percpu_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
1816 union bpf_attr __user *uattr)
1818 return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1823 htab_percpu_map_lookup_and_delete_batch(struct bpf_map *map,
1824 const union bpf_attr *attr,
1825 union bpf_attr __user *uattr)
1827 return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1832 htab_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
1833 union bpf_attr __user *uattr)
1835 return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1840 htab_map_lookup_and_delete_batch(struct bpf_map *map,
1841 const union bpf_attr *attr,
1842 union bpf_attr __user *uattr)
1844 return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1849 htab_lru_percpu_map_lookup_batch(struct bpf_map *map,
1850 const union bpf_attr *attr,
1851 union bpf_attr __user *uattr)
1853 return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1858 htab_lru_percpu_map_lookup_and_delete_batch(struct bpf_map *map,
1859 const union bpf_attr *attr,
1860 union bpf_attr __user *uattr)
1862 return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1867 htab_lru_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
1868 union bpf_attr __user *uattr)
1870 return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1875 htab_lru_map_lookup_and_delete_batch(struct bpf_map *map,
1876 const union bpf_attr *attr,
1877 union bpf_attr __user *uattr)
1879 return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1883 struct bpf_iter_seq_hash_map_info {
1884 struct bpf_map *map;
1885 struct bpf_htab *htab;
1886 void *percpu_value_buf; // non-zero means percpu hash
1891 static struct htab_elem *
1892 bpf_hash_map_seq_find_next(struct bpf_iter_seq_hash_map_info *info,
1893 struct htab_elem *prev_elem)
1895 const struct bpf_htab *htab = info->htab;
1896 u32 skip_elems = info->skip_elems;
1897 u32 bucket_id = info->bucket_id;
1898 struct hlist_nulls_head *head;
1899 struct hlist_nulls_node *n;
1900 struct htab_elem *elem;
1904 if (bucket_id >= htab->n_buckets)
1907 /* try to find next elem in the same bucket */
1909 /* no update/deletion on this bucket, prev_elem should be still valid
1910 * and we won't skip elements.
1912 n = rcu_dereference_raw(hlist_nulls_next_rcu(&prev_elem->hash_node));
1913 elem = hlist_nulls_entry_safe(n, struct htab_elem, hash_node);
1917 /* not found, unlock and go to the next bucket */
1918 b = &htab->buckets[bucket_id++];
1923 for (i = bucket_id; i < htab->n_buckets; i++) {
1924 b = &htab->buckets[i];
1929 hlist_nulls_for_each_entry_rcu(elem, n, head, hash_node) {
1930 if (count >= skip_elems) {
1931 info->bucket_id = i;
1932 info->skip_elems = count;
1942 info->bucket_id = i;
1943 info->skip_elems = 0;
1947 static void *bpf_hash_map_seq_start(struct seq_file *seq, loff_t *pos)
1949 struct bpf_iter_seq_hash_map_info *info = seq->private;
1950 struct htab_elem *elem;
1952 elem = bpf_hash_map_seq_find_next(info, NULL);
1961 static void *bpf_hash_map_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1963 struct bpf_iter_seq_hash_map_info *info = seq->private;
1967 return bpf_hash_map_seq_find_next(info, v);
1970 static int __bpf_hash_map_seq_show(struct seq_file *seq, struct htab_elem *elem)
1972 struct bpf_iter_seq_hash_map_info *info = seq->private;
1973 u32 roundup_key_size, roundup_value_size;
1974 struct bpf_iter__bpf_map_elem ctx = {};
1975 struct bpf_map *map = info->map;
1976 struct bpf_iter_meta meta;
1977 int ret = 0, off = 0, cpu;
1978 struct bpf_prog *prog;
1979 void __percpu *pptr;
1982 prog = bpf_iter_get_info(&meta, elem == NULL);
1985 ctx.map = info->map;
1987 roundup_key_size = round_up(map->key_size, 8);
1988 ctx.key = elem->key;
1989 if (!info->percpu_value_buf) {
1990 ctx.value = elem->key + roundup_key_size;
1992 roundup_value_size = round_up(map->value_size, 8);
1993 pptr = htab_elem_get_ptr(elem, map->key_size);
1994 for_each_possible_cpu(cpu) {
1995 bpf_long_memcpy(info->percpu_value_buf + off,
1996 per_cpu_ptr(pptr, cpu),
1997 roundup_value_size);
1998 off += roundup_value_size;
2000 ctx.value = info->percpu_value_buf;
2003 ret = bpf_iter_run_prog(prog, &ctx);
2009 static int bpf_hash_map_seq_show(struct seq_file *seq, void *v)
2011 return __bpf_hash_map_seq_show(seq, v);
2014 static void bpf_hash_map_seq_stop(struct seq_file *seq, void *v)
2017 (void)__bpf_hash_map_seq_show(seq, NULL);
2022 static int bpf_iter_init_hash_map(void *priv_data,
2023 struct bpf_iter_aux_info *aux)
2025 struct bpf_iter_seq_hash_map_info *seq_info = priv_data;
2026 struct bpf_map *map = aux->map;
2030 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
2031 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
2032 buf_size = round_up(map->value_size, 8) * num_possible_cpus();
2033 value_buf = kmalloc(buf_size, GFP_USER | __GFP_NOWARN);
2037 seq_info->percpu_value_buf = value_buf;
2040 bpf_map_inc_with_uref(map);
2041 seq_info->map = map;
2042 seq_info->htab = container_of(map, struct bpf_htab, map);
2046 static void bpf_iter_fini_hash_map(void *priv_data)
2048 struct bpf_iter_seq_hash_map_info *seq_info = priv_data;
2050 bpf_map_put_with_uref(seq_info->map);
2051 kfree(seq_info->percpu_value_buf);
2054 static const struct seq_operations bpf_hash_map_seq_ops = {
2055 .start = bpf_hash_map_seq_start,
2056 .next = bpf_hash_map_seq_next,
2057 .stop = bpf_hash_map_seq_stop,
2058 .show = bpf_hash_map_seq_show,
2061 static const struct bpf_iter_seq_info iter_seq_info = {
2062 .seq_ops = &bpf_hash_map_seq_ops,
2063 .init_seq_private = bpf_iter_init_hash_map,
2064 .fini_seq_private = bpf_iter_fini_hash_map,
2065 .seq_priv_size = sizeof(struct bpf_iter_seq_hash_map_info),
2068 static int bpf_for_each_hash_elem(struct bpf_map *map, void *callback_fn,
2069 void *callback_ctx, u64 flags)
2071 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2072 struct hlist_nulls_head *head;
2073 struct hlist_nulls_node *n;
2074 struct htab_elem *elem;
2075 u32 roundup_key_size;
2076 int i, num_elems = 0;
2077 void __percpu *pptr;
2086 is_percpu = htab_is_percpu(htab);
2088 roundup_key_size = round_up(map->key_size, 8);
2089 /* disable migration so percpu value prepared here will be the
2090 * same as the one seen by the bpf program with bpf_map_lookup_elem().
2094 for (i = 0; i < htab->n_buckets; i++) {
2095 b = &htab->buckets[i];
2098 hlist_nulls_for_each_entry_rcu(elem, n, head, hash_node) {
2101 /* current cpu value for percpu map */
2102 pptr = htab_elem_get_ptr(elem, map->key_size);
2103 val = this_cpu_ptr(pptr);
2105 val = elem->key + roundup_key_size;
2108 ret = BPF_CAST_CALL(callback_fn)((u64)(long)map,
2109 (u64)(long)key, (u64)(long)val,
2110 (u64)(long)callback_ctx, 0);
2111 /* return value: 0 - continue, 1 - stop and return */
2125 static int htab_map_btf_id;
2126 const struct bpf_map_ops htab_map_ops = {
2127 .map_meta_equal = bpf_map_meta_equal,
2128 .map_alloc_check = htab_map_alloc_check,
2129 .map_alloc = htab_map_alloc,
2130 .map_free = htab_map_free,
2131 .map_get_next_key = htab_map_get_next_key,
2132 .map_release_uref = htab_map_free_timers,
2133 .map_lookup_elem = htab_map_lookup_elem,
2134 .map_lookup_and_delete_elem = htab_map_lookup_and_delete_elem,
2135 .map_update_elem = htab_map_update_elem,
2136 .map_delete_elem = htab_map_delete_elem,
2137 .map_gen_lookup = htab_map_gen_lookup,
2138 .map_seq_show_elem = htab_map_seq_show_elem,
2139 .map_set_for_each_callback_args = map_set_for_each_callback_args,
2140 .map_for_each_callback = bpf_for_each_hash_elem,
2142 .map_btf_name = "bpf_htab",
2143 .map_btf_id = &htab_map_btf_id,
2144 .iter_seq_info = &iter_seq_info,
2147 static int htab_lru_map_btf_id;
2148 const struct bpf_map_ops htab_lru_map_ops = {
2149 .map_meta_equal = bpf_map_meta_equal,
2150 .map_alloc_check = htab_map_alloc_check,
2151 .map_alloc = htab_map_alloc,
2152 .map_free = htab_map_free,
2153 .map_get_next_key = htab_map_get_next_key,
2154 .map_release_uref = htab_map_free_timers,
2155 .map_lookup_elem = htab_lru_map_lookup_elem,
2156 .map_lookup_and_delete_elem = htab_lru_map_lookup_and_delete_elem,
2157 .map_lookup_elem_sys_only = htab_lru_map_lookup_elem_sys,
2158 .map_update_elem = htab_lru_map_update_elem,
2159 .map_delete_elem = htab_lru_map_delete_elem,
2160 .map_gen_lookup = htab_lru_map_gen_lookup,
2161 .map_seq_show_elem = htab_map_seq_show_elem,
2162 .map_set_for_each_callback_args = map_set_for_each_callback_args,
2163 .map_for_each_callback = bpf_for_each_hash_elem,
2164 BATCH_OPS(htab_lru),
2165 .map_btf_name = "bpf_htab",
2166 .map_btf_id = &htab_lru_map_btf_id,
2167 .iter_seq_info = &iter_seq_info,
2170 /* Called from eBPF program */
2171 static void *htab_percpu_map_lookup_elem(struct bpf_map *map, void *key)
2173 struct htab_elem *l = __htab_map_lookup_elem(map, key);
2176 return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size));
2181 static void *htab_lru_percpu_map_lookup_elem(struct bpf_map *map, void *key)
2183 struct htab_elem *l = __htab_map_lookup_elem(map, key);
2186 bpf_lru_node_set_ref(&l->lru_node);
2187 return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size));
2193 int bpf_percpu_hash_copy(struct bpf_map *map, void *key, void *value)
2195 struct htab_elem *l;
2196 void __percpu *pptr;
2201 /* per_cpu areas are zero-filled and bpf programs can only
2202 * access 'value_size' of them, so copying rounded areas
2203 * will not leak any kernel data
2205 size = round_up(map->value_size, 8);
2207 l = __htab_map_lookup_elem(map, key);
2210 /* We do not mark LRU map element here in order to not mess up
2211 * eviction heuristics when user space does a map walk.
2213 pptr = htab_elem_get_ptr(l, map->key_size);
2214 for_each_possible_cpu(cpu) {
2215 bpf_long_memcpy(value + off,
2216 per_cpu_ptr(pptr, cpu), size);
2225 int bpf_percpu_hash_update(struct bpf_map *map, void *key, void *value,
2228 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2232 if (htab_is_lru(htab))
2233 ret = __htab_lru_percpu_map_update_elem(map, key, value,
2236 ret = __htab_percpu_map_update_elem(map, key, value, map_flags,
2243 static void htab_percpu_map_seq_show_elem(struct bpf_map *map, void *key,
2246 struct htab_elem *l;
2247 void __percpu *pptr;
2252 l = __htab_map_lookup_elem(map, key);
2258 btf_type_seq_show(map->btf, map->btf_key_type_id, key, m);
2259 seq_puts(m, ": {\n");
2260 pptr = htab_elem_get_ptr(l, map->key_size);
2261 for_each_possible_cpu(cpu) {
2262 seq_printf(m, "\tcpu%d: ", cpu);
2263 btf_type_seq_show(map->btf, map->btf_value_type_id,
2264 per_cpu_ptr(pptr, cpu), m);
2272 static int htab_percpu_map_btf_id;
2273 const struct bpf_map_ops htab_percpu_map_ops = {
2274 .map_meta_equal = bpf_map_meta_equal,
2275 .map_alloc_check = htab_map_alloc_check,
2276 .map_alloc = htab_map_alloc,
2277 .map_free = htab_map_free,
2278 .map_get_next_key = htab_map_get_next_key,
2279 .map_lookup_elem = htab_percpu_map_lookup_elem,
2280 .map_lookup_and_delete_elem = htab_percpu_map_lookup_and_delete_elem,
2281 .map_update_elem = htab_percpu_map_update_elem,
2282 .map_delete_elem = htab_map_delete_elem,
2283 .map_seq_show_elem = htab_percpu_map_seq_show_elem,
2284 .map_set_for_each_callback_args = map_set_for_each_callback_args,
2285 .map_for_each_callback = bpf_for_each_hash_elem,
2286 BATCH_OPS(htab_percpu),
2287 .map_btf_name = "bpf_htab",
2288 .map_btf_id = &htab_percpu_map_btf_id,
2289 .iter_seq_info = &iter_seq_info,
2292 static int htab_lru_percpu_map_btf_id;
2293 const struct bpf_map_ops htab_lru_percpu_map_ops = {
2294 .map_meta_equal = bpf_map_meta_equal,
2295 .map_alloc_check = htab_map_alloc_check,
2296 .map_alloc = htab_map_alloc,
2297 .map_free = htab_map_free,
2298 .map_get_next_key = htab_map_get_next_key,
2299 .map_lookup_elem = htab_lru_percpu_map_lookup_elem,
2300 .map_lookup_and_delete_elem = htab_lru_percpu_map_lookup_and_delete_elem,
2301 .map_update_elem = htab_lru_percpu_map_update_elem,
2302 .map_delete_elem = htab_lru_map_delete_elem,
2303 .map_seq_show_elem = htab_percpu_map_seq_show_elem,
2304 .map_set_for_each_callback_args = map_set_for_each_callback_args,
2305 .map_for_each_callback = bpf_for_each_hash_elem,
2306 BATCH_OPS(htab_lru_percpu),
2307 .map_btf_name = "bpf_htab",
2308 .map_btf_id = &htab_lru_percpu_map_btf_id,
2309 .iter_seq_info = &iter_seq_info,
2312 static int fd_htab_map_alloc_check(union bpf_attr *attr)
2314 if (attr->value_size != sizeof(u32))
2316 return htab_map_alloc_check(attr);
2319 static void fd_htab_map_free(struct bpf_map *map)
2321 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2322 struct hlist_nulls_node *n;
2323 struct hlist_nulls_head *head;
2324 struct htab_elem *l;
2327 for (i = 0; i < htab->n_buckets; i++) {
2328 head = select_bucket(htab, i);
2330 hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
2331 void *ptr = fd_htab_map_get_ptr(map, l);
2333 map->ops->map_fd_put_ptr(ptr);
2340 /* only called from syscall */
2341 int bpf_fd_htab_map_lookup_elem(struct bpf_map *map, void *key, u32 *value)
2346 if (!map->ops->map_fd_sys_lookup_elem)
2350 ptr = htab_map_lookup_elem(map, key);
2352 *value = map->ops->map_fd_sys_lookup_elem(READ_ONCE(*ptr));
2360 /* only called from syscall */
2361 int bpf_fd_htab_map_update_elem(struct bpf_map *map, struct file *map_file,
2362 void *key, void *value, u64 map_flags)
2366 u32 ufd = *(u32 *)value;
2368 ptr = map->ops->map_fd_get_ptr(map, map_file, ufd);
2370 return PTR_ERR(ptr);
2372 ret = htab_map_update_elem(map, key, &ptr, map_flags);
2374 map->ops->map_fd_put_ptr(ptr);
2379 static struct bpf_map *htab_of_map_alloc(union bpf_attr *attr)
2381 struct bpf_map *map, *inner_map_meta;
2383 inner_map_meta = bpf_map_meta_alloc(attr->inner_map_fd);
2384 if (IS_ERR(inner_map_meta))
2385 return inner_map_meta;
2387 map = htab_map_alloc(attr);
2389 bpf_map_meta_free(inner_map_meta);
2393 map->inner_map_meta = inner_map_meta;
2398 static void *htab_of_map_lookup_elem(struct bpf_map *map, void *key)
2400 struct bpf_map **inner_map = htab_map_lookup_elem(map, key);
2405 return READ_ONCE(*inner_map);
2408 static int htab_of_map_gen_lookup(struct bpf_map *map,
2409 struct bpf_insn *insn_buf)
2411 struct bpf_insn *insn = insn_buf;
2412 const int ret = BPF_REG_0;
2414 BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
2415 (void *(*)(struct bpf_map *map, void *key))NULL));
2416 *insn++ = BPF_EMIT_CALL(BPF_CAST_CALL(__htab_map_lookup_elem));
2417 *insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 2);
2418 *insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
2419 offsetof(struct htab_elem, key) +
2420 round_up(map->key_size, 8));
2421 *insn++ = BPF_LDX_MEM(BPF_DW, ret, ret, 0);
2423 return insn - insn_buf;
2426 static void htab_of_map_free(struct bpf_map *map)
2428 bpf_map_meta_free(map->inner_map_meta);
2429 fd_htab_map_free(map);
2432 static int htab_of_maps_map_btf_id;
2433 const struct bpf_map_ops htab_of_maps_map_ops = {
2434 .map_alloc_check = fd_htab_map_alloc_check,
2435 .map_alloc = htab_of_map_alloc,
2436 .map_free = htab_of_map_free,
2437 .map_get_next_key = htab_map_get_next_key,
2438 .map_lookup_elem = htab_of_map_lookup_elem,
2439 .map_delete_elem = htab_map_delete_elem,
2440 .map_fd_get_ptr = bpf_map_fd_get_ptr,
2441 .map_fd_put_ptr = bpf_map_fd_put_ptr,
2442 .map_fd_sys_lookup_elem = bpf_map_fd_sys_lookup_elem,
2443 .map_gen_lookup = htab_of_map_gen_lookup,
2444 .map_check_btf = map_check_no_btf,
2445 .map_btf_name = "bpf_htab",
2446 .map_btf_id = &htab_of_maps_map_btf_id,