1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */
4 #include <linux/llist.h>
6 #include <linux/irq_work.h>
7 #include <linux/bpf_mem_alloc.h>
8 #include <linux/memcontrol.h>
11 /* Any context (including NMI) BPF specific memory allocator.
13 * Tracing BPF programs can attach to kprobe and fentry. Hence they
14 * run in unknown context where calling plain kmalloc() might not be safe.
16 * Front-end kmalloc() with per-cpu per-bucket cache of free elements.
17 * Refill this cache asynchronously from irq_work.
20 * 16 32 64 96 128 196 256 512 1024 2048 4096
23 * 16 32 64 96 128 196 256 512 1024 2048 4096
25 * The buckets are prefilled at the start.
26 * BPF programs always run with migration disabled.
27 * It's safe to allocate from cache of the current cpu with irqs disabled.
28 * Free-ing is always done into bucket of the current cpu as well.
29 * irq_work trims extra free elements from buckets with kfree
30 * and refills them with kmalloc, so global kmalloc logic takes care
31 * of freeing objects allocated by one cpu and freed on another.
33 * Every allocated objected is padded with extra 8 bytes that contains
36 #define LLIST_NODE_SZ sizeof(struct llist_node)
38 /* similar to kmalloc, but sizeof == 8 bucket is gone */
39 static u8 size_index[24] __ro_after_init = {
66 static int bpf_mem_cache_idx(size_t size)
68 if (!size || size > 4096)
72 return size_index[(size - 1) / 8] - 1;
74 return fls(size - 1) - 2;
79 struct bpf_mem_cache {
80 /* per-cpu list of free objects of size 'unit_size'.
81 * All accesses are done with interrupts disabled and 'active' counter
82 * protection with __llist_add() and __llist_del_first().
84 struct llist_head free_llist;
87 /* Operations on the free_list from unit_alloc/unit_free/bpf_mem_refill
88 * are sequenced by per-cpu 'active' counter. But unit_free() cannot
89 * fail. When 'active' is busy the unit_free() will add an object to
92 struct llist_head free_llist_extra;
94 struct irq_work refill_work;
95 struct obj_cgroup *objcg;
97 /* count of objects in free_llist */
99 int low_watermark, high_watermark, batch;
103 struct llist_head free_by_rcu;
104 struct llist_head waiting_for_gp;
105 atomic_t call_rcu_in_progress;
108 struct bpf_mem_caches {
109 struct bpf_mem_cache cache[NUM_CACHES];
112 static struct llist_node notrace *__llist_del_first(struct llist_head *head)
114 struct llist_node *entry, *next;
124 static void *__alloc(struct bpf_mem_cache *c, int node, gfp_t flags)
126 if (c->percpu_size) {
127 void **obj = kmalloc_node(c->percpu_size, flags, node);
128 void *pptr = __alloc_percpu_gfp(c->unit_size, 8, flags);
139 return kmalloc_node(c->unit_size, flags | __GFP_ZERO, node);
142 static struct mem_cgroup *get_memcg(const struct bpf_mem_cache *c)
144 #ifdef CONFIG_MEMCG_KMEM
146 return get_mem_cgroup_from_objcg(c->objcg);
150 return root_mem_cgroup;
156 /* Mostly runs from irq_work except __init phase. */
157 static void alloc_bulk(struct bpf_mem_cache *c, int cnt, int node)
159 struct mem_cgroup *memcg = NULL, *old_memcg;
164 memcg = get_memcg(c);
165 old_memcg = set_active_memcg(memcg);
166 for (i = 0; i < cnt; i++) {
168 * free_by_rcu is only manipulated by irq work refill_work().
169 * IRQ works on the same CPU are called sequentially, so it is
170 * safe to use __llist_del_first() here. If alloc_bulk() is
171 * invoked by the initial prefill, there will be no running
172 * refill_work(), so __llist_del_first() is fine as well.
174 * In most cases, objects on free_by_rcu are from the same CPU.
175 * If some objects come from other CPUs, it doesn't incur any
176 * harm because NUMA_NO_NODE means the preference for current
177 * numa node and it is not a guarantee.
179 obj = __llist_del_first(&c->free_by_rcu);
181 /* Allocate, but don't deplete atomic reserves that typical
182 * GFP_ATOMIC would do. irq_work runs on this cpu and kmalloc
183 * will allocate from the current numa node which is what we
186 obj = __alloc(c, node, GFP_NOWAIT | __GFP_NOWARN | __GFP_ACCOUNT);
190 if (IS_ENABLED(CONFIG_PREEMPT_RT))
191 /* In RT irq_work runs in per-cpu kthread, so disable
192 * interrupts to avoid preemption and interrupts and
193 * reduce the chance of bpf prog executing on this cpu
194 * when active counter is busy.
196 local_irq_save(flags);
197 /* alloc_bulk runs from irq_work which will not preempt a bpf
198 * program that does unit_alloc/unit_free since IRQs are
199 * disabled there. There is no race to increment 'active'
200 * counter. It protects free_llist from corruption in case NMI
201 * bpf prog preempted this loop.
203 WARN_ON_ONCE(local_inc_return(&c->active) != 1);
204 __llist_add(obj, &c->free_llist);
206 local_dec(&c->active);
207 if (IS_ENABLED(CONFIG_PREEMPT_RT))
208 local_irq_restore(flags);
210 set_active_memcg(old_memcg);
211 mem_cgroup_put(memcg);
214 static void free_one(void *obj, bool percpu)
217 free_percpu(((void **)obj)[1]);
225 static void free_all(struct llist_node *llnode, bool percpu)
227 struct llist_node *pos, *t;
229 llist_for_each_safe(pos, t, llnode)
230 free_one(pos, percpu);
233 static void __free_rcu(struct rcu_head *head)
235 struct bpf_mem_cache *c = container_of(head, struct bpf_mem_cache, rcu);
237 free_all(llist_del_all(&c->waiting_for_gp), !!c->percpu_size);
238 atomic_set(&c->call_rcu_in_progress, 0);
241 static void __free_rcu_tasks_trace(struct rcu_head *head)
243 /* If RCU Tasks Trace grace period implies RCU grace period,
244 * there is no need to invoke call_rcu().
246 if (rcu_trace_implies_rcu_gp())
249 call_rcu(head, __free_rcu);
252 static void enque_to_free(struct bpf_mem_cache *c, void *obj)
254 struct llist_node *llnode = obj;
256 /* bpf_mem_cache is a per-cpu object. Freeing happens in irq_work.
257 * Nothing races to add to free_by_rcu list.
259 __llist_add(llnode, &c->free_by_rcu);
262 static void do_call_rcu(struct bpf_mem_cache *c)
264 struct llist_node *llnode, *t;
266 if (atomic_xchg(&c->call_rcu_in_progress, 1))
269 WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp));
270 llist_for_each_safe(llnode, t, __llist_del_all(&c->free_by_rcu))
271 /* There is no concurrent __llist_add(waiting_for_gp) access.
272 * It doesn't race with llist_del_all either.
273 * But there could be two concurrent llist_del_all(waiting_for_gp):
274 * from __free_rcu() and from drain_mem_cache().
276 __llist_add(llnode, &c->waiting_for_gp);
277 /* Use call_rcu_tasks_trace() to wait for sleepable progs to finish.
278 * If RCU Tasks Trace grace period implies RCU grace period, free
279 * these elements directly, else use call_rcu() to wait for normal
280 * progs to finish and finally do free_one() on each element.
282 call_rcu_tasks_trace(&c->rcu, __free_rcu_tasks_trace);
285 static void free_bulk(struct bpf_mem_cache *c)
287 struct llist_node *llnode, *t;
292 if (IS_ENABLED(CONFIG_PREEMPT_RT))
293 local_irq_save(flags);
294 WARN_ON_ONCE(local_inc_return(&c->active) != 1);
295 llnode = __llist_del_first(&c->free_llist);
300 local_dec(&c->active);
301 if (IS_ENABLED(CONFIG_PREEMPT_RT))
302 local_irq_restore(flags);
304 enque_to_free(c, llnode);
305 } while (cnt > (c->high_watermark + c->low_watermark) / 2);
307 /* and drain free_llist_extra */
308 llist_for_each_safe(llnode, t, llist_del_all(&c->free_llist_extra))
309 enque_to_free(c, llnode);
313 static void bpf_mem_refill(struct irq_work *work)
315 struct bpf_mem_cache *c = container_of(work, struct bpf_mem_cache, refill_work);
318 /* Racy access to free_cnt. It doesn't need to be 100% accurate */
320 if (cnt < c->low_watermark)
321 /* irq_work runs on this cpu and kmalloc will allocate
322 * from the current numa node which is what we want here.
324 alloc_bulk(c, c->batch, NUMA_NO_NODE);
325 else if (cnt > c->high_watermark)
329 static void notrace irq_work_raise(struct bpf_mem_cache *c)
331 irq_work_queue(&c->refill_work);
334 /* For typical bpf map case that uses bpf_mem_cache_alloc and single bucket
335 * the freelist cache will be elem_size * 64 (or less) on each cpu.
337 * For bpf programs that don't have statically known allocation sizes and
338 * assuming (low_mark + high_mark) / 2 as an average number of elements per
339 * bucket and all buckets are used the total amount of memory in freelists
340 * on each cpu will be:
341 * 64*16 + 64*32 + 64*64 + 64*96 + 64*128 + 64*196 + 64*256 + 32*512 + 16*1024 + 8*2048 + 4*4096
342 * == ~ 116 Kbyte using below heuristic.
343 * Initialized, but unused bpf allocator (not bpf map specific one) will
344 * consume ~ 11 Kbyte per cpu.
345 * Typical case will be between 11K and 116K closer to 11K.
346 * bpf progs can and should share bpf_mem_cache when possible.
349 static void prefill_mem_cache(struct bpf_mem_cache *c, int cpu)
351 init_irq_work(&c->refill_work, bpf_mem_refill);
352 if (c->unit_size <= 256) {
353 c->low_watermark = 32;
354 c->high_watermark = 96;
356 /* When page_size == 4k, order-0 cache will have low_mark == 2
357 * and high_mark == 6 with batch alloc of 3 individual pages at
359 * 8k allocs and above low == 1, high == 3, batch == 1.
361 c->low_watermark = max(32 * 256 / c->unit_size, 1);
362 c->high_watermark = max(96 * 256 / c->unit_size, 3);
364 c->batch = max((c->high_watermark - c->low_watermark) / 4 * 3, 1);
366 /* To avoid consuming memory assume that 1st run of bpf
367 * prog won't be doing more than 4 map_update_elem from
368 * irq disabled region
370 alloc_bulk(c, c->unit_size <= 256 ? 4 : 1, cpu_to_node(cpu));
373 /* When size != 0 bpf_mem_cache for each cpu.
374 * This is typical bpf hash map use case when all elements have equal size.
376 * When size == 0 allocate 11 bpf_mem_cache-s for each cpu, then rely on
377 * kmalloc/kfree. Max allocation size is 4096 in this case.
378 * This is bpf_dynptr and bpf_kptr use case.
380 int bpf_mem_alloc_init(struct bpf_mem_alloc *ma, int size, bool percpu)
382 static u16 sizes[NUM_CACHES] = {96, 192, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096};
383 struct bpf_mem_caches *cc, __percpu *pcc;
384 struct bpf_mem_cache *c, __percpu *pc;
385 struct obj_cgroup *objcg = NULL;
386 int cpu, i, unit_size, percpu_size = 0;
389 pc = __alloc_percpu_gfp(sizeof(*pc), 8, GFP_KERNEL);
394 /* room for llist_node and per-cpu pointer */
395 percpu_size = LLIST_NODE_SZ + sizeof(void *);
397 size += LLIST_NODE_SZ; /* room for llist_node */
400 #ifdef CONFIG_MEMCG_KMEM
401 if (memcg_bpf_enabled())
402 objcg = get_obj_cgroup_from_current();
404 for_each_possible_cpu(cpu) {
405 c = per_cpu_ptr(pc, cpu);
406 c->unit_size = unit_size;
408 c->percpu_size = percpu_size;
409 prefill_mem_cache(c, cpu);
415 /* size == 0 && percpu is an invalid combination */
416 if (WARN_ON_ONCE(percpu))
419 pcc = __alloc_percpu_gfp(sizeof(*cc), 8, GFP_KERNEL);
422 #ifdef CONFIG_MEMCG_KMEM
423 objcg = get_obj_cgroup_from_current();
425 for_each_possible_cpu(cpu) {
426 cc = per_cpu_ptr(pcc, cpu);
427 for (i = 0; i < NUM_CACHES; i++) {
429 c->unit_size = sizes[i];
431 prefill_mem_cache(c, cpu);
438 static void drain_mem_cache(struct bpf_mem_cache *c)
440 bool percpu = !!c->percpu_size;
442 /* No progs are using this bpf_mem_cache, but htab_map_free() called
443 * bpf_mem_cache_free() for all remaining elements and they can be in
444 * free_by_rcu or in waiting_for_gp lists, so drain those lists now.
446 * Except for waiting_for_gp list, there are no concurrent operations
447 * on these lists, so it is safe to use __llist_del_all().
449 free_all(__llist_del_all(&c->free_by_rcu), percpu);
450 free_all(llist_del_all(&c->waiting_for_gp), percpu);
451 free_all(__llist_del_all(&c->free_llist), percpu);
452 free_all(__llist_del_all(&c->free_llist_extra), percpu);
455 static void free_mem_alloc_no_barrier(struct bpf_mem_alloc *ma)
457 free_percpu(ma->cache);
458 free_percpu(ma->caches);
463 static void free_mem_alloc(struct bpf_mem_alloc *ma)
465 /* waiting_for_gp lists was drained, but __free_rcu might
466 * still execute. Wait for it now before we freeing percpu caches.
468 * rcu_barrier_tasks_trace() doesn't imply synchronize_rcu_tasks_trace(),
469 * but rcu_barrier_tasks_trace() and rcu_barrier() below are only used
470 * to wait for the pending __free_rcu_tasks_trace() and __free_rcu(),
471 * so if call_rcu(head, __free_rcu) is skipped due to
472 * rcu_trace_implies_rcu_gp(), it will be OK to skip rcu_barrier() by
473 * using rcu_trace_implies_rcu_gp() as well.
475 rcu_barrier_tasks_trace();
476 if (!rcu_trace_implies_rcu_gp())
478 free_mem_alloc_no_barrier(ma);
481 static void free_mem_alloc_deferred(struct work_struct *work)
483 struct bpf_mem_alloc *ma = container_of(work, struct bpf_mem_alloc, work);
489 static void destroy_mem_alloc(struct bpf_mem_alloc *ma, int rcu_in_progress)
491 struct bpf_mem_alloc *copy;
493 if (!rcu_in_progress) {
494 /* Fast path. No callbacks are pending, hence no need to do
497 free_mem_alloc_no_barrier(ma);
501 copy = kmalloc(sizeof(*ma), GFP_KERNEL);
503 /* Slow path with inline barrier-s */
508 /* Defer barriers into worker to let the rest of map memory to be freed */
509 copy->cache = ma->cache;
511 copy->caches = ma->caches;
513 INIT_WORK(©->work, free_mem_alloc_deferred);
514 queue_work(system_unbound_wq, ©->work);
517 void bpf_mem_alloc_destroy(struct bpf_mem_alloc *ma)
519 struct bpf_mem_caches *cc;
520 struct bpf_mem_cache *c;
521 int cpu, i, rcu_in_progress;
525 for_each_possible_cpu(cpu) {
526 c = per_cpu_ptr(ma->cache, cpu);
528 * refill_work may be unfinished for PREEMPT_RT kernel
529 * in which irq work is invoked in a per-CPU RT thread.
530 * It is also possible for kernel with
531 * arch_irq_work_has_interrupt() being false and irq
532 * work is invoked in timer interrupt. So waiting for
533 * the completion of irq work to ease the handling of
536 irq_work_sync(&c->refill_work);
538 rcu_in_progress += atomic_read(&c->call_rcu_in_progress);
540 /* objcg is the same across cpus */
542 obj_cgroup_put(c->objcg);
543 destroy_mem_alloc(ma, rcu_in_progress);
547 for_each_possible_cpu(cpu) {
548 cc = per_cpu_ptr(ma->caches, cpu);
549 for (i = 0; i < NUM_CACHES; i++) {
551 irq_work_sync(&c->refill_work);
553 rcu_in_progress += atomic_read(&c->call_rcu_in_progress);
557 obj_cgroup_put(c->objcg);
558 destroy_mem_alloc(ma, rcu_in_progress);
562 /* notrace is necessary here and in other functions to make sure
563 * bpf programs cannot attach to them and cause llist corruptions.
565 static void notrace *unit_alloc(struct bpf_mem_cache *c)
567 struct llist_node *llnode = NULL;
571 /* Disable irqs to prevent the following race for majority of prog types:
574 * preemption or irq -> prog_B
577 * but prog_B could be a perf_event NMI prog.
578 * Use per-cpu 'active' counter to order free_list access between
579 * unit_alloc/unit_free/bpf_mem_refill.
581 local_irq_save(flags);
582 if (local_inc_return(&c->active) == 1) {
583 llnode = __llist_del_first(&c->free_llist);
587 local_dec(&c->active);
588 local_irq_restore(flags);
592 if (cnt < c->low_watermark)
597 /* Though 'ptr' object could have been allocated on a different cpu
598 * add it to the free_llist of the current cpu.
599 * Let kfree() logic deal with it when it's later called from irq_work.
601 static void notrace unit_free(struct bpf_mem_cache *c, void *ptr)
603 struct llist_node *llnode = ptr - LLIST_NODE_SZ;
607 BUILD_BUG_ON(LLIST_NODE_SZ > 8);
609 local_irq_save(flags);
610 if (local_inc_return(&c->active) == 1) {
611 __llist_add(llnode, &c->free_llist);
614 /* unit_free() cannot fail. Therefore add an object to atomic
615 * llist. free_bulk() will drain it. Though free_llist_extra is
616 * a per-cpu list we have to use atomic llist_add here, since
617 * it also can be interrupted by bpf nmi prog that does another
618 * unit_free() into the same free_llist_extra.
620 llist_add(llnode, &c->free_llist_extra);
622 local_dec(&c->active);
623 local_irq_restore(flags);
625 if (cnt > c->high_watermark)
626 /* free few objects from current cpu into global kmalloc pool */
630 /* Called from BPF program or from sys_bpf syscall.
631 * In both cases migration is disabled.
633 void notrace *bpf_mem_alloc(struct bpf_mem_alloc *ma, size_t size)
639 return ZERO_SIZE_PTR;
641 idx = bpf_mem_cache_idx(size + LLIST_NODE_SZ);
645 ret = unit_alloc(this_cpu_ptr(ma->caches)->cache + idx);
646 return !ret ? NULL : ret + LLIST_NODE_SZ;
649 void notrace bpf_mem_free(struct bpf_mem_alloc *ma, void *ptr)
656 idx = bpf_mem_cache_idx(ksize(ptr - LLIST_NODE_SZ));
660 unit_free(this_cpu_ptr(ma->caches)->cache + idx, ptr);
663 void notrace *bpf_mem_cache_alloc(struct bpf_mem_alloc *ma)
667 ret = unit_alloc(this_cpu_ptr(ma->cache));
668 return !ret ? NULL : ret + LLIST_NODE_SZ;
671 void notrace bpf_mem_cache_free(struct bpf_mem_alloc *ma, void *ptr)
676 unit_free(this_cpu_ptr(ma->cache), ptr);
679 /* Directly does a kfree() without putting 'ptr' back to the free_llist
680 * for reuse and without waiting for a rcu_tasks_trace gp.
681 * The caller must first go through the rcu_tasks_trace gp for 'ptr'
682 * before calling bpf_mem_cache_raw_free().
683 * It could be used when the rcu_tasks_trace callback does not have
684 * a hold on the original bpf_mem_alloc object that allocated the
685 * 'ptr'. This should only be used in the uncommon code path.
686 * Otherwise, the bpf_mem_alloc's free_llist cannot be refilled
687 * and may affect performance.
689 void bpf_mem_cache_raw_free(void *ptr)
694 kfree(ptr - LLIST_NODE_SZ);
697 /* When flags == GFP_KERNEL, it signals that the caller will not cause
698 * deadlock when using kmalloc. bpf_mem_cache_alloc_flags() will use
699 * kmalloc if the free_llist is empty.
701 void notrace *bpf_mem_cache_alloc_flags(struct bpf_mem_alloc *ma, gfp_t flags)
703 struct bpf_mem_cache *c;
706 c = this_cpu_ptr(ma->cache);
709 if (!ret && flags == GFP_KERNEL) {
710 struct mem_cgroup *memcg, *old_memcg;
712 memcg = get_memcg(c);
713 old_memcg = set_active_memcg(memcg);
714 ret = __alloc(c, NUMA_NO_NODE, GFP_KERNEL | __GFP_NOWARN | __GFP_ACCOUNT);
715 set_active_memcg(old_memcg);
716 mem_cgroup_put(memcg);
719 return !ret ? NULL : ret + LLIST_NODE_SZ;