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;
102 struct bpf_mem_cache *tgt;
104 /* list of objects to be freed after RCU GP */
105 struct llist_head free_by_rcu;
106 struct llist_node *free_by_rcu_tail;
107 struct llist_head waiting_for_gp;
108 struct llist_node *waiting_for_gp_tail;
110 atomic_t call_rcu_in_progress;
111 struct llist_head free_llist_extra_rcu;
113 /* list of objects to be freed after RCU tasks trace GP */
114 struct llist_head free_by_rcu_ttrace;
115 struct llist_head waiting_for_gp_ttrace;
116 struct rcu_head rcu_ttrace;
117 atomic_t call_rcu_ttrace_in_progress;
120 struct bpf_mem_caches {
121 struct bpf_mem_cache cache[NUM_CACHES];
124 static struct llist_node notrace *__llist_del_first(struct llist_head *head)
126 struct llist_node *entry, *next;
136 static void *__alloc(struct bpf_mem_cache *c, int node, gfp_t flags)
138 if (c->percpu_size) {
139 void **obj = kmalloc_node(c->percpu_size, flags, node);
140 void *pptr = __alloc_percpu_gfp(c->unit_size, 8, flags);
151 return kmalloc_node(c->unit_size, flags | __GFP_ZERO, node);
154 static struct mem_cgroup *get_memcg(const struct bpf_mem_cache *c)
156 #ifdef CONFIG_MEMCG_KMEM
158 return get_mem_cgroup_from_objcg(c->objcg);
162 return root_mem_cgroup;
168 static void inc_active(struct bpf_mem_cache *c, unsigned long *flags)
170 if (IS_ENABLED(CONFIG_PREEMPT_RT))
171 /* In RT irq_work runs in per-cpu kthread, so disable
172 * interrupts to avoid preemption and interrupts and
173 * reduce the chance of bpf prog executing on this cpu
174 * when active counter is busy.
176 local_irq_save(*flags);
177 /* alloc_bulk runs from irq_work which will not preempt a bpf
178 * program that does unit_alloc/unit_free since IRQs are
179 * disabled there. There is no race to increment 'active'
180 * counter. It protects free_llist from corruption in case NMI
181 * bpf prog preempted this loop.
183 WARN_ON_ONCE(local_inc_return(&c->active) != 1);
186 static void dec_active(struct bpf_mem_cache *c, unsigned long *flags)
188 local_dec(&c->active);
189 if (IS_ENABLED(CONFIG_PREEMPT_RT))
190 local_irq_restore(*flags);
193 static void add_obj_to_free_list(struct bpf_mem_cache *c, void *obj)
197 inc_active(c, &flags);
198 __llist_add(obj, &c->free_llist);
200 dec_active(c, &flags);
203 /* Mostly runs from irq_work except __init phase. */
204 static void alloc_bulk(struct bpf_mem_cache *c, int cnt, int node, bool atomic)
206 struct mem_cgroup *memcg = NULL, *old_memcg;
211 gfp = __GFP_NOWARN | __GFP_ACCOUNT;
212 gfp |= atomic ? GFP_NOWAIT : GFP_KERNEL;
214 for (i = 0; i < cnt; i++) {
216 * For every 'c' llist_del_first(&c->free_by_rcu_ttrace); is
217 * done only by one CPU == current CPU. Other CPUs might
218 * llist_add() and llist_del_all() in parallel.
220 obj = llist_del_first(&c->free_by_rcu_ttrace);
223 add_obj_to_free_list(c, obj);
228 for (; i < cnt; i++) {
229 obj = llist_del_first(&c->waiting_for_gp_ttrace);
232 add_obj_to_free_list(c, obj);
237 memcg = get_memcg(c);
238 old_memcg = set_active_memcg(memcg);
239 for (; i < cnt; i++) {
240 /* Allocate, but don't deplete atomic reserves that typical
241 * GFP_ATOMIC would do. irq_work runs on this cpu and kmalloc
242 * will allocate from the current numa node which is what we
245 obj = __alloc(c, node, gfp);
248 add_obj_to_free_list(c, obj);
250 set_active_memcg(old_memcg);
251 mem_cgroup_put(memcg);
254 static void free_one(void *obj, bool percpu)
257 free_percpu(((void **)obj)[1]);
265 static int free_all(struct llist_node *llnode, bool percpu)
267 struct llist_node *pos, *t;
270 llist_for_each_safe(pos, t, llnode) {
271 free_one(pos, percpu);
277 static void __free_rcu(struct rcu_head *head)
279 struct bpf_mem_cache *c = container_of(head, struct bpf_mem_cache, rcu_ttrace);
281 free_all(llist_del_all(&c->waiting_for_gp_ttrace), !!c->percpu_size);
282 atomic_set(&c->call_rcu_ttrace_in_progress, 0);
285 static void __free_rcu_tasks_trace(struct rcu_head *head)
287 /* If RCU Tasks Trace grace period implies RCU grace period,
288 * there is no need to invoke call_rcu().
290 if (rcu_trace_implies_rcu_gp())
293 call_rcu(head, __free_rcu);
296 static void enque_to_free(struct bpf_mem_cache *c, void *obj)
298 struct llist_node *llnode = obj;
300 /* bpf_mem_cache is a per-cpu object. Freeing happens in irq_work.
301 * Nothing races to add to free_by_rcu_ttrace list.
303 llist_add(llnode, &c->free_by_rcu_ttrace);
306 static void do_call_rcu_ttrace(struct bpf_mem_cache *c)
308 struct llist_node *llnode, *t;
310 if (atomic_xchg(&c->call_rcu_ttrace_in_progress, 1)) {
311 if (unlikely(READ_ONCE(c->draining))) {
312 llnode = llist_del_all(&c->free_by_rcu_ttrace);
313 free_all(llnode, !!c->percpu_size);
318 WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp_ttrace));
319 llist_for_each_safe(llnode, t, llist_del_all(&c->free_by_rcu_ttrace))
320 llist_add(llnode, &c->waiting_for_gp_ttrace);
322 if (unlikely(READ_ONCE(c->draining))) {
323 __free_rcu(&c->rcu_ttrace);
327 /* Use call_rcu_tasks_trace() to wait for sleepable progs to finish.
328 * If RCU Tasks Trace grace period implies RCU grace period, free
329 * these elements directly, else use call_rcu() to wait for normal
330 * progs to finish and finally do free_one() on each element.
332 call_rcu_tasks_trace(&c->rcu_ttrace, __free_rcu_tasks_trace);
335 static void free_bulk(struct bpf_mem_cache *c)
337 struct bpf_mem_cache *tgt = c->tgt;
338 struct llist_node *llnode, *t;
342 WARN_ON_ONCE(tgt->unit_size != c->unit_size);
345 inc_active(c, &flags);
346 llnode = __llist_del_first(&c->free_llist);
351 dec_active(c, &flags);
353 enque_to_free(tgt, llnode);
354 } while (cnt > (c->high_watermark + c->low_watermark) / 2);
356 /* and drain free_llist_extra */
357 llist_for_each_safe(llnode, t, llist_del_all(&c->free_llist_extra))
358 enque_to_free(tgt, llnode);
359 do_call_rcu_ttrace(tgt);
362 static void __free_by_rcu(struct rcu_head *head)
364 struct bpf_mem_cache *c = container_of(head, struct bpf_mem_cache, rcu);
365 struct bpf_mem_cache *tgt = c->tgt;
366 struct llist_node *llnode;
368 llnode = llist_del_all(&c->waiting_for_gp);
372 llist_add_batch(llnode, c->waiting_for_gp_tail, &tgt->free_by_rcu_ttrace);
374 /* Objects went through regular RCU GP. Send them to RCU tasks trace */
375 do_call_rcu_ttrace(tgt);
377 atomic_set(&c->call_rcu_in_progress, 0);
380 static void check_free_by_rcu(struct bpf_mem_cache *c)
382 struct llist_node *llnode, *t;
385 /* drain free_llist_extra_rcu */
386 if (unlikely(!llist_empty(&c->free_llist_extra_rcu))) {
387 inc_active(c, &flags);
388 llist_for_each_safe(llnode, t, llist_del_all(&c->free_llist_extra_rcu))
389 if (__llist_add(llnode, &c->free_by_rcu))
390 c->free_by_rcu_tail = llnode;
391 dec_active(c, &flags);
394 if (llist_empty(&c->free_by_rcu))
397 if (atomic_xchg(&c->call_rcu_in_progress, 1)) {
399 * Instead of kmalloc-ing new rcu_head and triggering 10k
400 * call_rcu() to hit rcutree.qhimark and force RCU to notice
401 * the overload just ask RCU to hurry up. There could be many
402 * objects in free_by_rcu list.
403 * This hint reduces memory consumption for an artificial
404 * benchmark from 2 Gbyte to 150 Mbyte.
406 rcu_request_urgent_qs_task(current);
410 WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp));
412 inc_active(c, &flags);
413 WRITE_ONCE(c->waiting_for_gp.first, __llist_del_all(&c->free_by_rcu));
414 c->waiting_for_gp_tail = c->free_by_rcu_tail;
415 dec_active(c, &flags);
417 if (unlikely(READ_ONCE(c->draining))) {
418 free_all(llist_del_all(&c->waiting_for_gp), !!c->percpu_size);
419 atomic_set(&c->call_rcu_in_progress, 0);
421 call_rcu_hurry(&c->rcu, __free_by_rcu);
425 static void bpf_mem_refill(struct irq_work *work)
427 struct bpf_mem_cache *c = container_of(work, struct bpf_mem_cache, refill_work);
430 /* Racy access to free_cnt. It doesn't need to be 100% accurate */
432 if (cnt < c->low_watermark)
433 /* irq_work runs on this cpu and kmalloc will allocate
434 * from the current numa node which is what we want here.
436 alloc_bulk(c, c->batch, NUMA_NO_NODE, true);
437 else if (cnt > c->high_watermark)
440 check_free_by_rcu(c);
443 static void notrace irq_work_raise(struct bpf_mem_cache *c)
445 irq_work_queue(&c->refill_work);
448 /* For typical bpf map case that uses bpf_mem_cache_alloc and single bucket
449 * the freelist cache will be elem_size * 64 (or less) on each cpu.
451 * For bpf programs that don't have statically known allocation sizes and
452 * assuming (low_mark + high_mark) / 2 as an average number of elements per
453 * bucket and all buckets are used the total amount of memory in freelists
454 * on each cpu will be:
455 * 64*16 + 64*32 + 64*64 + 64*96 + 64*128 + 64*196 + 64*256 + 32*512 + 16*1024 + 8*2048 + 4*4096
456 * == ~ 116 Kbyte using below heuristic.
457 * Initialized, but unused bpf allocator (not bpf map specific one) will
458 * consume ~ 11 Kbyte per cpu.
459 * Typical case will be between 11K and 116K closer to 11K.
460 * bpf progs can and should share bpf_mem_cache when possible.
462 static void init_refill_work(struct bpf_mem_cache *c)
464 init_irq_work(&c->refill_work, bpf_mem_refill);
465 if (c->unit_size <= 256) {
466 c->low_watermark = 32;
467 c->high_watermark = 96;
469 /* When page_size == 4k, order-0 cache will have low_mark == 2
470 * and high_mark == 6 with batch alloc of 3 individual pages at
472 * 8k allocs and above low == 1, high == 3, batch == 1.
474 c->low_watermark = max(32 * 256 / c->unit_size, 1);
475 c->high_watermark = max(96 * 256 / c->unit_size, 3);
477 c->batch = max((c->high_watermark - c->low_watermark) / 4 * 3, 1);
480 static void prefill_mem_cache(struct bpf_mem_cache *c, int cpu)
482 /* To avoid consuming memory assume that 1st run of bpf
483 * prog won't be doing more than 4 map_update_elem from
484 * irq disabled region
486 alloc_bulk(c, c->unit_size <= 256 ? 4 : 1, cpu_to_node(cpu), false);
489 /* When size != 0 bpf_mem_cache for each cpu.
490 * This is typical bpf hash map use case when all elements have equal size.
492 * When size == 0 allocate 11 bpf_mem_cache-s for each cpu, then rely on
493 * kmalloc/kfree. Max allocation size is 4096 in this case.
494 * This is bpf_dynptr and bpf_kptr use case.
496 int bpf_mem_alloc_init(struct bpf_mem_alloc *ma, int size, bool percpu)
498 static u16 sizes[NUM_CACHES] = {96, 192, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096};
499 struct bpf_mem_caches *cc, __percpu *pcc;
500 struct bpf_mem_cache *c, __percpu *pc;
501 struct obj_cgroup *objcg = NULL;
502 int cpu, i, unit_size, percpu_size = 0;
507 pc = __alloc_percpu_gfp(sizeof(*pc), 8, GFP_KERNEL);
512 /* room for llist_node and per-cpu pointer */
513 percpu_size = LLIST_NODE_SZ + sizeof(void *);
515 size += LLIST_NODE_SZ; /* room for llist_node */
518 #ifdef CONFIG_MEMCG_KMEM
519 if (memcg_bpf_enabled())
520 objcg = get_obj_cgroup_from_current();
522 for_each_possible_cpu(cpu) {
523 c = per_cpu_ptr(pc, cpu);
524 c->unit_size = unit_size;
526 c->percpu_size = percpu_size;
529 prefill_mem_cache(c, cpu);
535 /* size == 0 && percpu is an invalid combination */
536 if (WARN_ON_ONCE(percpu))
539 pcc = __alloc_percpu_gfp(sizeof(*cc), 8, GFP_KERNEL);
542 #ifdef CONFIG_MEMCG_KMEM
543 objcg = get_obj_cgroup_from_current();
545 for_each_possible_cpu(cpu) {
546 cc = per_cpu_ptr(pcc, cpu);
547 for (i = 0; i < NUM_CACHES; i++) {
549 c->unit_size = sizes[i];
554 prefill_mem_cache(c, cpu);
562 static void drain_mem_cache(struct bpf_mem_cache *c)
564 bool percpu = !!c->percpu_size;
566 /* No progs are using this bpf_mem_cache, but htab_map_free() called
567 * bpf_mem_cache_free() for all remaining elements and they can be in
568 * free_by_rcu_ttrace or in waiting_for_gp_ttrace lists, so drain those lists now.
570 * Except for waiting_for_gp_ttrace list, there are no concurrent operations
571 * on these lists, so it is safe to use __llist_del_all().
573 free_all(llist_del_all(&c->free_by_rcu_ttrace), percpu);
574 free_all(llist_del_all(&c->waiting_for_gp_ttrace), percpu);
575 free_all(__llist_del_all(&c->free_llist), percpu);
576 free_all(__llist_del_all(&c->free_llist_extra), percpu);
577 free_all(__llist_del_all(&c->free_by_rcu), percpu);
578 free_all(__llist_del_all(&c->free_llist_extra_rcu), percpu);
579 free_all(llist_del_all(&c->waiting_for_gp), percpu);
582 static void check_mem_cache(struct bpf_mem_cache *c)
584 WARN_ON_ONCE(!llist_empty(&c->free_by_rcu_ttrace));
585 WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp_ttrace));
586 WARN_ON_ONCE(!llist_empty(&c->free_llist));
587 WARN_ON_ONCE(!llist_empty(&c->free_llist_extra));
588 WARN_ON_ONCE(!llist_empty(&c->free_by_rcu));
589 WARN_ON_ONCE(!llist_empty(&c->free_llist_extra_rcu));
590 WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp));
593 static void check_leaked_objs(struct bpf_mem_alloc *ma)
595 struct bpf_mem_caches *cc;
596 struct bpf_mem_cache *c;
600 for_each_possible_cpu(cpu) {
601 c = per_cpu_ptr(ma->cache, cpu);
606 for_each_possible_cpu(cpu) {
607 cc = per_cpu_ptr(ma->caches, cpu);
608 for (i = 0; i < NUM_CACHES; i++) {
616 static void free_mem_alloc_no_barrier(struct bpf_mem_alloc *ma)
618 check_leaked_objs(ma);
619 free_percpu(ma->cache);
620 free_percpu(ma->caches);
625 static void free_mem_alloc(struct bpf_mem_alloc *ma)
627 /* waiting_for_gp[_ttrace] lists were drained, but RCU callbacks
628 * might still execute. Wait for them.
630 * rcu_barrier_tasks_trace() doesn't imply synchronize_rcu_tasks_trace(),
631 * but rcu_barrier_tasks_trace() and rcu_barrier() below are only used
632 * to wait for the pending __free_rcu_tasks_trace() and __free_rcu(),
633 * so if call_rcu(head, __free_rcu) is skipped due to
634 * rcu_trace_implies_rcu_gp(), it will be OK to skip rcu_barrier() by
635 * using rcu_trace_implies_rcu_gp() as well.
637 rcu_barrier(); /* wait for __free_by_rcu */
638 rcu_barrier_tasks_trace(); /* wait for __free_rcu */
639 if (!rcu_trace_implies_rcu_gp())
641 free_mem_alloc_no_barrier(ma);
644 static void free_mem_alloc_deferred(struct work_struct *work)
646 struct bpf_mem_alloc *ma = container_of(work, struct bpf_mem_alloc, work);
652 static void destroy_mem_alloc(struct bpf_mem_alloc *ma, int rcu_in_progress)
654 struct bpf_mem_alloc *copy;
656 if (!rcu_in_progress) {
657 /* Fast path. No callbacks are pending, hence no need to do
660 free_mem_alloc_no_barrier(ma);
664 copy = kmemdup(ma, sizeof(*ma), GFP_KERNEL);
666 /* Slow path with inline barrier-s */
671 /* Defer barriers into worker to let the rest of map memory to be freed */
672 memset(ma, 0, sizeof(*ma));
673 INIT_WORK(©->work, free_mem_alloc_deferred);
674 queue_work(system_unbound_wq, ©->work);
677 void bpf_mem_alloc_destroy(struct bpf_mem_alloc *ma)
679 struct bpf_mem_caches *cc;
680 struct bpf_mem_cache *c;
681 int cpu, i, rcu_in_progress;
685 for_each_possible_cpu(cpu) {
686 c = per_cpu_ptr(ma->cache, cpu);
687 WRITE_ONCE(c->draining, true);
688 irq_work_sync(&c->refill_work);
690 rcu_in_progress += atomic_read(&c->call_rcu_ttrace_in_progress);
691 rcu_in_progress += atomic_read(&c->call_rcu_in_progress);
693 /* objcg is the same across cpus */
695 obj_cgroup_put(c->objcg);
696 destroy_mem_alloc(ma, rcu_in_progress);
700 for_each_possible_cpu(cpu) {
701 cc = per_cpu_ptr(ma->caches, cpu);
702 for (i = 0; i < NUM_CACHES; i++) {
704 WRITE_ONCE(c->draining, true);
705 irq_work_sync(&c->refill_work);
707 rcu_in_progress += atomic_read(&c->call_rcu_ttrace_in_progress);
708 rcu_in_progress += atomic_read(&c->call_rcu_in_progress);
712 obj_cgroup_put(c->objcg);
713 destroy_mem_alloc(ma, rcu_in_progress);
717 /* notrace is necessary here and in other functions to make sure
718 * bpf programs cannot attach to them and cause llist corruptions.
720 static void notrace *unit_alloc(struct bpf_mem_cache *c)
722 struct llist_node *llnode = NULL;
726 /* Disable irqs to prevent the following race for majority of prog types:
729 * preemption or irq -> prog_B
732 * but prog_B could be a perf_event NMI prog.
733 * Use per-cpu 'active' counter to order free_list access between
734 * unit_alloc/unit_free/bpf_mem_refill.
736 local_irq_save(flags);
737 if (local_inc_return(&c->active) == 1) {
738 llnode = __llist_del_first(&c->free_llist);
741 *(struct bpf_mem_cache **)llnode = c;
744 local_dec(&c->active);
745 local_irq_restore(flags);
749 if (cnt < c->low_watermark)
754 /* Though 'ptr' object could have been allocated on a different cpu
755 * add it to the free_llist of the current cpu.
756 * Let kfree() logic deal with it when it's later called from irq_work.
758 static void notrace unit_free(struct bpf_mem_cache *c, void *ptr)
760 struct llist_node *llnode = ptr - LLIST_NODE_SZ;
764 BUILD_BUG_ON(LLIST_NODE_SZ > 8);
767 * Remember bpf_mem_cache that allocated this object.
768 * The hint is not accurate.
770 c->tgt = *(struct bpf_mem_cache **)llnode;
772 local_irq_save(flags);
773 if (local_inc_return(&c->active) == 1) {
774 __llist_add(llnode, &c->free_llist);
777 /* unit_free() cannot fail. Therefore add an object to atomic
778 * llist. free_bulk() will drain it. Though free_llist_extra is
779 * a per-cpu list we have to use atomic llist_add here, since
780 * it also can be interrupted by bpf nmi prog that does another
781 * unit_free() into the same free_llist_extra.
783 llist_add(llnode, &c->free_llist_extra);
785 local_dec(&c->active);
786 local_irq_restore(flags);
788 if (cnt > c->high_watermark)
789 /* free few objects from current cpu into global kmalloc pool */
793 static void notrace unit_free_rcu(struct bpf_mem_cache *c, void *ptr)
795 struct llist_node *llnode = ptr - LLIST_NODE_SZ;
798 c->tgt = *(struct bpf_mem_cache **)llnode;
800 local_irq_save(flags);
801 if (local_inc_return(&c->active) == 1) {
802 if (__llist_add(llnode, &c->free_by_rcu))
803 c->free_by_rcu_tail = llnode;
805 llist_add(llnode, &c->free_llist_extra_rcu);
807 local_dec(&c->active);
808 local_irq_restore(flags);
810 if (!atomic_read(&c->call_rcu_in_progress))
814 /* Called from BPF program or from sys_bpf syscall.
815 * In both cases migration is disabled.
817 void notrace *bpf_mem_alloc(struct bpf_mem_alloc *ma, size_t size)
825 idx = bpf_mem_cache_idx(size + LLIST_NODE_SZ);
829 ret = unit_alloc(this_cpu_ptr(ma->caches)->cache + idx);
830 return !ret ? NULL : ret + LLIST_NODE_SZ;
833 void notrace bpf_mem_free(struct bpf_mem_alloc *ma, void *ptr)
835 struct bpf_mem_cache *c;
841 c = *(void **)(ptr - LLIST_NODE_SZ);
842 idx = bpf_mem_cache_idx(c->unit_size);
843 if (WARN_ON_ONCE(idx < 0))
846 unit_free(this_cpu_ptr(ma->caches)->cache + idx, ptr);
849 void notrace bpf_mem_free_rcu(struct bpf_mem_alloc *ma, void *ptr)
851 struct bpf_mem_cache *c;
857 c = *(void **)(ptr - LLIST_NODE_SZ);
858 idx = bpf_mem_cache_idx(c->unit_size);
859 if (WARN_ON_ONCE(idx < 0))
862 unit_free_rcu(this_cpu_ptr(ma->caches)->cache + idx, ptr);
865 void notrace *bpf_mem_cache_alloc(struct bpf_mem_alloc *ma)
869 ret = unit_alloc(this_cpu_ptr(ma->cache));
870 return !ret ? NULL : ret + LLIST_NODE_SZ;
873 void notrace bpf_mem_cache_free(struct bpf_mem_alloc *ma, void *ptr)
878 unit_free(this_cpu_ptr(ma->cache), ptr);
881 void notrace bpf_mem_cache_free_rcu(struct bpf_mem_alloc *ma, void *ptr)
886 unit_free_rcu(this_cpu_ptr(ma->cache), ptr);
889 /* Directly does a kfree() without putting 'ptr' back to the free_llist
890 * for reuse and without waiting for a rcu_tasks_trace gp.
891 * The caller must first go through the rcu_tasks_trace gp for 'ptr'
892 * before calling bpf_mem_cache_raw_free().
893 * It could be used when the rcu_tasks_trace callback does not have
894 * a hold on the original bpf_mem_alloc object that allocated the
895 * 'ptr'. This should only be used in the uncommon code path.
896 * Otherwise, the bpf_mem_alloc's free_llist cannot be refilled
897 * and may affect performance.
899 void bpf_mem_cache_raw_free(void *ptr)
904 kfree(ptr - LLIST_NODE_SZ);
907 /* When flags == GFP_KERNEL, it signals that the caller will not cause
908 * deadlock when using kmalloc. bpf_mem_cache_alloc_flags() will use
909 * kmalloc if the free_llist is empty.
911 void notrace *bpf_mem_cache_alloc_flags(struct bpf_mem_alloc *ma, gfp_t flags)
913 struct bpf_mem_cache *c;
916 c = this_cpu_ptr(ma->cache);
919 if (!ret && flags == GFP_KERNEL) {
920 struct mem_cgroup *memcg, *old_memcg;
922 memcg = get_memcg(c);
923 old_memcg = set_active_memcg(memcg);
924 ret = __alloc(c, NUMA_NO_NODE, GFP_KERNEL | __GFP_NOWARN | __GFP_ACCOUNT);
926 *(struct bpf_mem_cache **)ret = c;
927 set_active_memcg(old_memcg);
928 mem_cgroup_put(memcg);
931 return !ret ? NULL : ret + LLIST_NODE_SZ;