Merge tag 'sound-6.4-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/tiwai...
[linux-block.git] / kernel / bpf / memalloc.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */
3 #include <linux/mm.h>
4 #include <linux/llist.h>
5 #include <linux/bpf.h>
6 #include <linux/irq_work.h>
7 #include <linux/bpf_mem_alloc.h>
8 #include <linux/memcontrol.h>
9 #include <asm/local.h>
10
11 /* Any context (including NMI) BPF specific memory allocator.
12  *
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.
15  *
16  * Front-end kmalloc() with per-cpu per-bucket cache of free elements.
17  * Refill this cache asynchronously from irq_work.
18  *
19  * CPU_0 buckets
20  * 16 32 64 96 128 196 256 512 1024 2048 4096
21  * ...
22  * CPU_N buckets
23  * 16 32 64 96 128 196 256 512 1024 2048 4096
24  *
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.
32  *
33  * Every allocated objected is padded with extra 8 bytes that contains
34  * struct llist_node.
35  */
36 #define LLIST_NODE_SZ sizeof(struct llist_node)
37
38 /* similar to kmalloc, but sizeof == 8 bucket is gone */
39 static u8 size_index[24] __ro_after_init = {
40         3,      /* 8 */
41         3,      /* 16 */
42         4,      /* 24 */
43         4,      /* 32 */
44         5,      /* 40 */
45         5,      /* 48 */
46         5,      /* 56 */
47         5,      /* 64 */
48         1,      /* 72 */
49         1,      /* 80 */
50         1,      /* 88 */
51         1,      /* 96 */
52         6,      /* 104 */
53         6,      /* 112 */
54         6,      /* 120 */
55         6,      /* 128 */
56         2,      /* 136 */
57         2,      /* 144 */
58         2,      /* 152 */
59         2,      /* 160 */
60         2,      /* 168 */
61         2,      /* 176 */
62         2,      /* 184 */
63         2       /* 192 */
64 };
65
66 static int bpf_mem_cache_idx(size_t size)
67 {
68         if (!size || size > 4096)
69                 return -1;
70
71         if (size <= 192)
72                 return size_index[(size - 1) / 8] - 1;
73
74         return fls(size - 1) - 2;
75 }
76
77 #define NUM_CACHES 11
78
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().
83          */
84         struct llist_head free_llist;
85         local_t active;
86
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
90          * free_llist_extra.
91          */
92         struct llist_head free_llist_extra;
93
94         struct irq_work refill_work;
95         struct obj_cgroup *objcg;
96         int unit_size;
97         /* count of objects in free_llist */
98         int free_cnt;
99         int low_watermark, high_watermark, batch;
100         int percpu_size;
101
102         struct rcu_head rcu;
103         struct llist_head free_by_rcu;
104         struct llist_head waiting_for_gp;
105         atomic_t call_rcu_in_progress;
106 };
107
108 struct bpf_mem_caches {
109         struct bpf_mem_cache cache[NUM_CACHES];
110 };
111
112 static struct llist_node notrace *__llist_del_first(struct llist_head *head)
113 {
114         struct llist_node *entry, *next;
115
116         entry = head->first;
117         if (!entry)
118                 return NULL;
119         next = entry->next;
120         head->first = next;
121         return entry;
122 }
123
124 static void *__alloc(struct bpf_mem_cache *c, int node, gfp_t flags)
125 {
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);
129
130                 if (!obj || !pptr) {
131                         free_percpu(pptr);
132                         kfree(obj);
133                         return NULL;
134                 }
135                 obj[1] = pptr;
136                 return obj;
137         }
138
139         return kmalloc_node(c->unit_size, flags | __GFP_ZERO, node);
140 }
141
142 static struct mem_cgroup *get_memcg(const struct bpf_mem_cache *c)
143 {
144 #ifdef CONFIG_MEMCG_KMEM
145         if (c->objcg)
146                 return get_mem_cgroup_from_objcg(c->objcg);
147 #endif
148
149 #ifdef CONFIG_MEMCG
150         return root_mem_cgroup;
151 #else
152         return NULL;
153 #endif
154 }
155
156 /* Mostly runs from irq_work except __init phase. */
157 static void alloc_bulk(struct bpf_mem_cache *c, int cnt, int node)
158 {
159         struct mem_cgroup *memcg = NULL, *old_memcg;
160         unsigned long flags;
161         void *obj;
162         int i;
163
164         memcg = get_memcg(c);
165         old_memcg = set_active_memcg(memcg);
166         for (i = 0; i < cnt; i++) {
167                 /*
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.
173                  *
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.
178                  */
179                 obj = __llist_del_first(&c->free_by_rcu);
180                 if (!obj) {
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
184                          * want here.
185                          */
186                         obj = __alloc(c, node, GFP_NOWAIT | __GFP_NOWARN | __GFP_ACCOUNT);
187                         if (!obj)
188                                 break;
189                 }
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.
195                          */
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.
202                  */
203                 WARN_ON_ONCE(local_inc_return(&c->active) != 1);
204                 __llist_add(obj, &c->free_llist);
205                 c->free_cnt++;
206                 local_dec(&c->active);
207                 if (IS_ENABLED(CONFIG_PREEMPT_RT))
208                         local_irq_restore(flags);
209         }
210         set_active_memcg(old_memcg);
211         mem_cgroup_put(memcg);
212 }
213
214 static void free_one(struct bpf_mem_cache *c, void *obj)
215 {
216         if (c->percpu_size) {
217                 free_percpu(((void **)obj)[1]);
218                 kfree(obj);
219                 return;
220         }
221
222         kfree(obj);
223 }
224
225 static void __free_rcu(struct rcu_head *head)
226 {
227         struct bpf_mem_cache *c = container_of(head, struct bpf_mem_cache, rcu);
228         struct llist_node *llnode = llist_del_all(&c->waiting_for_gp);
229         struct llist_node *pos, *t;
230
231         llist_for_each_safe(pos, t, llnode)
232                 free_one(c, pos);
233         atomic_set(&c->call_rcu_in_progress, 0);
234 }
235
236 static void __free_rcu_tasks_trace(struct rcu_head *head)
237 {
238         /* If RCU Tasks Trace grace period implies RCU grace period,
239          * there is no need to invoke call_rcu().
240          */
241         if (rcu_trace_implies_rcu_gp())
242                 __free_rcu(head);
243         else
244                 call_rcu(head, __free_rcu);
245 }
246
247 static void enque_to_free(struct bpf_mem_cache *c, void *obj)
248 {
249         struct llist_node *llnode = obj;
250
251         /* bpf_mem_cache is a per-cpu object. Freeing happens in irq_work.
252          * Nothing races to add to free_by_rcu list.
253          */
254         __llist_add(llnode, &c->free_by_rcu);
255 }
256
257 static void do_call_rcu(struct bpf_mem_cache *c)
258 {
259         struct llist_node *llnode, *t;
260
261         if (atomic_xchg(&c->call_rcu_in_progress, 1))
262                 return;
263
264         WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp));
265         llist_for_each_safe(llnode, t, __llist_del_all(&c->free_by_rcu))
266                 /* There is no concurrent __llist_add(waiting_for_gp) access.
267                  * It doesn't race with llist_del_all either.
268                  * But there could be two concurrent llist_del_all(waiting_for_gp):
269                  * from __free_rcu() and from drain_mem_cache().
270                  */
271                 __llist_add(llnode, &c->waiting_for_gp);
272         /* Use call_rcu_tasks_trace() to wait for sleepable progs to finish.
273          * If RCU Tasks Trace grace period implies RCU grace period, free
274          * these elements directly, else use call_rcu() to wait for normal
275          * progs to finish and finally do free_one() on each element.
276          */
277         call_rcu_tasks_trace(&c->rcu, __free_rcu_tasks_trace);
278 }
279
280 static void free_bulk(struct bpf_mem_cache *c)
281 {
282         struct llist_node *llnode, *t;
283         unsigned long flags;
284         int cnt;
285
286         do {
287                 if (IS_ENABLED(CONFIG_PREEMPT_RT))
288                         local_irq_save(flags);
289                 WARN_ON_ONCE(local_inc_return(&c->active) != 1);
290                 llnode = __llist_del_first(&c->free_llist);
291                 if (llnode)
292                         cnt = --c->free_cnt;
293                 else
294                         cnt = 0;
295                 local_dec(&c->active);
296                 if (IS_ENABLED(CONFIG_PREEMPT_RT))
297                         local_irq_restore(flags);
298                 if (llnode)
299                         enque_to_free(c, llnode);
300         } while (cnt > (c->high_watermark + c->low_watermark) / 2);
301
302         /* and drain free_llist_extra */
303         llist_for_each_safe(llnode, t, llist_del_all(&c->free_llist_extra))
304                 enque_to_free(c, llnode);
305         do_call_rcu(c);
306 }
307
308 static void bpf_mem_refill(struct irq_work *work)
309 {
310         struct bpf_mem_cache *c = container_of(work, struct bpf_mem_cache, refill_work);
311         int cnt;
312
313         /* Racy access to free_cnt. It doesn't need to be 100% accurate */
314         cnt = c->free_cnt;
315         if (cnt < c->low_watermark)
316                 /* irq_work runs on this cpu and kmalloc will allocate
317                  * from the current numa node which is what we want here.
318                  */
319                 alloc_bulk(c, c->batch, NUMA_NO_NODE);
320         else if (cnt > c->high_watermark)
321                 free_bulk(c);
322 }
323
324 static void notrace irq_work_raise(struct bpf_mem_cache *c)
325 {
326         irq_work_queue(&c->refill_work);
327 }
328
329 /* For typical bpf map case that uses bpf_mem_cache_alloc and single bucket
330  * the freelist cache will be elem_size * 64 (or less) on each cpu.
331  *
332  * For bpf programs that don't have statically known allocation sizes and
333  * assuming (low_mark + high_mark) / 2 as an average number of elements per
334  * bucket and all buckets are used the total amount of memory in freelists
335  * on each cpu will be:
336  * 64*16 + 64*32 + 64*64 + 64*96 + 64*128 + 64*196 + 64*256 + 32*512 + 16*1024 + 8*2048 + 4*4096
337  * == ~ 116 Kbyte using below heuristic.
338  * Initialized, but unused bpf allocator (not bpf map specific one) will
339  * consume ~ 11 Kbyte per cpu.
340  * Typical case will be between 11K and 116K closer to 11K.
341  * bpf progs can and should share bpf_mem_cache when possible.
342  */
343
344 static void prefill_mem_cache(struct bpf_mem_cache *c, int cpu)
345 {
346         init_irq_work(&c->refill_work, bpf_mem_refill);
347         if (c->unit_size <= 256) {
348                 c->low_watermark = 32;
349                 c->high_watermark = 96;
350         } else {
351                 /* When page_size == 4k, order-0 cache will have low_mark == 2
352                  * and high_mark == 6 with batch alloc of 3 individual pages at
353                  * a time.
354                  * 8k allocs and above low == 1, high == 3, batch == 1.
355                  */
356                 c->low_watermark = max(32 * 256 / c->unit_size, 1);
357                 c->high_watermark = max(96 * 256 / c->unit_size, 3);
358         }
359         c->batch = max((c->high_watermark - c->low_watermark) / 4 * 3, 1);
360
361         /* To avoid consuming memory assume that 1st run of bpf
362          * prog won't be doing more than 4 map_update_elem from
363          * irq disabled region
364          */
365         alloc_bulk(c, c->unit_size <= 256 ? 4 : 1, cpu_to_node(cpu));
366 }
367
368 /* When size != 0 bpf_mem_cache for each cpu.
369  * This is typical bpf hash map use case when all elements have equal size.
370  *
371  * When size == 0 allocate 11 bpf_mem_cache-s for each cpu, then rely on
372  * kmalloc/kfree. Max allocation size is 4096 in this case.
373  * This is bpf_dynptr and bpf_kptr use case.
374  */
375 int bpf_mem_alloc_init(struct bpf_mem_alloc *ma, int size, bool percpu)
376 {
377         static u16 sizes[NUM_CACHES] = {96, 192, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096};
378         struct bpf_mem_caches *cc, __percpu *pcc;
379         struct bpf_mem_cache *c, __percpu *pc;
380         struct obj_cgroup *objcg = NULL;
381         int cpu, i, unit_size, percpu_size = 0;
382
383         if (size) {
384                 pc = __alloc_percpu_gfp(sizeof(*pc), 8, GFP_KERNEL);
385                 if (!pc)
386                         return -ENOMEM;
387
388                 if (percpu)
389                         /* room for llist_node and per-cpu pointer */
390                         percpu_size = LLIST_NODE_SZ + sizeof(void *);
391                 else
392                         size += LLIST_NODE_SZ; /* room for llist_node */
393                 unit_size = size;
394
395 #ifdef CONFIG_MEMCG_KMEM
396                 if (memcg_bpf_enabled())
397                         objcg = get_obj_cgroup_from_current();
398 #endif
399                 for_each_possible_cpu(cpu) {
400                         c = per_cpu_ptr(pc, cpu);
401                         c->unit_size = unit_size;
402                         c->objcg = objcg;
403                         c->percpu_size = percpu_size;
404                         prefill_mem_cache(c, cpu);
405                 }
406                 ma->cache = pc;
407                 return 0;
408         }
409
410         /* size == 0 && percpu is an invalid combination */
411         if (WARN_ON_ONCE(percpu))
412                 return -EINVAL;
413
414         pcc = __alloc_percpu_gfp(sizeof(*cc), 8, GFP_KERNEL);
415         if (!pcc)
416                 return -ENOMEM;
417 #ifdef CONFIG_MEMCG_KMEM
418         objcg = get_obj_cgroup_from_current();
419 #endif
420         for_each_possible_cpu(cpu) {
421                 cc = per_cpu_ptr(pcc, cpu);
422                 for (i = 0; i < NUM_CACHES; i++) {
423                         c = &cc->cache[i];
424                         c->unit_size = sizes[i];
425                         c->objcg = objcg;
426                         prefill_mem_cache(c, cpu);
427                 }
428         }
429         ma->caches = pcc;
430         return 0;
431 }
432
433 static void drain_mem_cache(struct bpf_mem_cache *c)
434 {
435         struct llist_node *llnode, *t;
436
437         /* No progs are using this bpf_mem_cache, but htab_map_free() called
438          * bpf_mem_cache_free() for all remaining elements and they can be in
439          * free_by_rcu or in waiting_for_gp lists, so drain those lists now.
440          *
441          * Except for waiting_for_gp list, there are no concurrent operations
442          * on these lists, so it is safe to use __llist_del_all().
443          */
444         llist_for_each_safe(llnode, t, __llist_del_all(&c->free_by_rcu))
445                 free_one(c, llnode);
446         llist_for_each_safe(llnode, t, llist_del_all(&c->waiting_for_gp))
447                 free_one(c, llnode);
448         llist_for_each_safe(llnode, t, __llist_del_all(&c->free_llist))
449                 free_one(c, llnode);
450         llist_for_each_safe(llnode, t, __llist_del_all(&c->free_llist_extra))
451                 free_one(c, llnode);
452 }
453
454 static void free_mem_alloc_no_barrier(struct bpf_mem_alloc *ma)
455 {
456         free_percpu(ma->cache);
457         free_percpu(ma->caches);
458         ma->cache = NULL;
459         ma->caches = NULL;
460 }
461
462 static void free_mem_alloc(struct bpf_mem_alloc *ma)
463 {
464         /* waiting_for_gp lists was drained, but __free_rcu might
465          * still execute. Wait for it now before we freeing percpu caches.
466          *
467          * rcu_barrier_tasks_trace() doesn't imply synchronize_rcu_tasks_trace(),
468          * but rcu_barrier_tasks_trace() and rcu_barrier() below are only used
469          * to wait for the pending __free_rcu_tasks_trace() and __free_rcu(),
470          * so if call_rcu(head, __free_rcu) is skipped due to
471          * rcu_trace_implies_rcu_gp(), it will be OK to skip rcu_barrier() by
472          * using rcu_trace_implies_rcu_gp() as well.
473          */
474         rcu_barrier_tasks_trace();
475         if (!rcu_trace_implies_rcu_gp())
476                 rcu_barrier();
477         free_mem_alloc_no_barrier(ma);
478 }
479
480 static void free_mem_alloc_deferred(struct work_struct *work)
481 {
482         struct bpf_mem_alloc *ma = container_of(work, struct bpf_mem_alloc, work);
483
484         free_mem_alloc(ma);
485         kfree(ma);
486 }
487
488 static void destroy_mem_alloc(struct bpf_mem_alloc *ma, int rcu_in_progress)
489 {
490         struct bpf_mem_alloc *copy;
491
492         if (!rcu_in_progress) {
493                 /* Fast path. No callbacks are pending, hence no need to do
494                  * rcu_barrier-s.
495                  */
496                 free_mem_alloc_no_barrier(ma);
497                 return;
498         }
499
500         copy = kmalloc(sizeof(*ma), GFP_KERNEL);
501         if (!copy) {
502                 /* Slow path with inline barrier-s */
503                 free_mem_alloc(ma);
504                 return;
505         }
506
507         /* Defer barriers into worker to let the rest of map memory to be freed */
508         copy->cache = ma->cache;
509         ma->cache = NULL;
510         copy->caches = ma->caches;
511         ma->caches = NULL;
512         INIT_WORK(&copy->work, free_mem_alloc_deferred);
513         queue_work(system_unbound_wq, &copy->work);
514 }
515
516 void bpf_mem_alloc_destroy(struct bpf_mem_alloc *ma)
517 {
518         struct bpf_mem_caches *cc;
519         struct bpf_mem_cache *c;
520         int cpu, i, rcu_in_progress;
521
522         if (ma->cache) {
523                 rcu_in_progress = 0;
524                 for_each_possible_cpu(cpu) {
525                         c = per_cpu_ptr(ma->cache, cpu);
526                         /*
527                          * refill_work may be unfinished for PREEMPT_RT kernel
528                          * in which irq work is invoked in a per-CPU RT thread.
529                          * It is also possible for kernel with
530                          * arch_irq_work_has_interrupt() being false and irq
531                          * work is invoked in timer interrupt. So waiting for
532                          * the completion of irq work to ease the handling of
533                          * concurrency.
534                          */
535                         irq_work_sync(&c->refill_work);
536                         drain_mem_cache(c);
537                         rcu_in_progress += atomic_read(&c->call_rcu_in_progress);
538                 }
539                 /* objcg is the same across cpus */
540                 if (c->objcg)
541                         obj_cgroup_put(c->objcg);
542                 destroy_mem_alloc(ma, rcu_in_progress);
543         }
544         if (ma->caches) {
545                 rcu_in_progress = 0;
546                 for_each_possible_cpu(cpu) {
547                         cc = per_cpu_ptr(ma->caches, cpu);
548                         for (i = 0; i < NUM_CACHES; i++) {
549                                 c = &cc->cache[i];
550                                 irq_work_sync(&c->refill_work);
551                                 drain_mem_cache(c);
552                                 rcu_in_progress += atomic_read(&c->call_rcu_in_progress);
553                         }
554                 }
555                 if (c->objcg)
556                         obj_cgroup_put(c->objcg);
557                 destroy_mem_alloc(ma, rcu_in_progress);
558         }
559 }
560
561 /* notrace is necessary here and in other functions to make sure
562  * bpf programs cannot attach to them and cause llist corruptions.
563  */
564 static void notrace *unit_alloc(struct bpf_mem_cache *c)
565 {
566         struct llist_node *llnode = NULL;
567         unsigned long flags;
568         int cnt = 0;
569
570         /* Disable irqs to prevent the following race for majority of prog types:
571          * prog_A
572          *   bpf_mem_alloc
573          *      preemption or irq -> prog_B
574          *        bpf_mem_alloc
575          *
576          * but prog_B could be a perf_event NMI prog.
577          * Use per-cpu 'active' counter to order free_list access between
578          * unit_alloc/unit_free/bpf_mem_refill.
579          */
580         local_irq_save(flags);
581         if (local_inc_return(&c->active) == 1) {
582                 llnode = __llist_del_first(&c->free_llist);
583                 if (llnode)
584                         cnt = --c->free_cnt;
585         }
586         local_dec(&c->active);
587         local_irq_restore(flags);
588
589         WARN_ON(cnt < 0);
590
591         if (cnt < c->low_watermark)
592                 irq_work_raise(c);
593         return llnode;
594 }
595
596 /* Though 'ptr' object could have been allocated on a different cpu
597  * add it to the free_llist of the current cpu.
598  * Let kfree() logic deal with it when it's later called from irq_work.
599  */
600 static void notrace unit_free(struct bpf_mem_cache *c, void *ptr)
601 {
602         struct llist_node *llnode = ptr - LLIST_NODE_SZ;
603         unsigned long flags;
604         int cnt = 0;
605
606         BUILD_BUG_ON(LLIST_NODE_SZ > 8);
607
608         local_irq_save(flags);
609         if (local_inc_return(&c->active) == 1) {
610                 __llist_add(llnode, &c->free_llist);
611                 cnt = ++c->free_cnt;
612         } else {
613                 /* unit_free() cannot fail. Therefore add an object to atomic
614                  * llist. free_bulk() will drain it. Though free_llist_extra is
615                  * a per-cpu list we have to use atomic llist_add here, since
616                  * it also can be interrupted by bpf nmi prog that does another
617                  * unit_free() into the same free_llist_extra.
618                  */
619                 llist_add(llnode, &c->free_llist_extra);
620         }
621         local_dec(&c->active);
622         local_irq_restore(flags);
623
624         if (cnt > c->high_watermark)
625                 /* free few objects from current cpu into global kmalloc pool */
626                 irq_work_raise(c);
627 }
628
629 /* Called from BPF program or from sys_bpf syscall.
630  * In both cases migration is disabled.
631  */
632 void notrace *bpf_mem_alloc(struct bpf_mem_alloc *ma, size_t size)
633 {
634         int idx;
635         void *ret;
636
637         if (!size)
638                 return ZERO_SIZE_PTR;
639
640         idx = bpf_mem_cache_idx(size + LLIST_NODE_SZ);
641         if (idx < 0)
642                 return NULL;
643
644         ret = unit_alloc(this_cpu_ptr(ma->caches)->cache + idx);
645         return !ret ? NULL : ret + LLIST_NODE_SZ;
646 }
647
648 void notrace bpf_mem_free(struct bpf_mem_alloc *ma, void *ptr)
649 {
650         int idx;
651
652         if (!ptr)
653                 return;
654
655         idx = bpf_mem_cache_idx(ksize(ptr - LLIST_NODE_SZ));
656         if (idx < 0)
657                 return;
658
659         unit_free(this_cpu_ptr(ma->caches)->cache + idx, ptr);
660 }
661
662 void notrace *bpf_mem_cache_alloc(struct bpf_mem_alloc *ma)
663 {
664         void *ret;
665
666         ret = unit_alloc(this_cpu_ptr(ma->cache));
667         return !ret ? NULL : ret + LLIST_NODE_SZ;
668 }
669
670 void notrace bpf_mem_cache_free(struct bpf_mem_alloc *ma, void *ptr)
671 {
672         if (!ptr)
673                 return;
674
675         unit_free(this_cpu_ptr(ma->cache), ptr);
676 }
677
678 /* Directly does a kfree() without putting 'ptr' back to the free_llist
679  * for reuse and without waiting for a rcu_tasks_trace gp.
680  * The caller must first go through the rcu_tasks_trace gp for 'ptr'
681  * before calling bpf_mem_cache_raw_free().
682  * It could be used when the rcu_tasks_trace callback does not have
683  * a hold on the original bpf_mem_alloc object that allocated the
684  * 'ptr'. This should only be used in the uncommon code path.
685  * Otherwise, the bpf_mem_alloc's free_llist cannot be refilled
686  * and may affect performance.
687  */
688 void bpf_mem_cache_raw_free(void *ptr)
689 {
690         if (!ptr)
691                 return;
692
693         kfree(ptr - LLIST_NODE_SZ);
694 }
695
696 /* When flags == GFP_KERNEL, it signals that the caller will not cause
697  * deadlock when using kmalloc. bpf_mem_cache_alloc_flags() will use
698  * kmalloc if the free_llist is empty.
699  */
700 void notrace *bpf_mem_cache_alloc_flags(struct bpf_mem_alloc *ma, gfp_t flags)
701 {
702         struct bpf_mem_cache *c;
703         void *ret;
704
705         c = this_cpu_ptr(ma->cache);
706
707         ret = unit_alloc(c);
708         if (!ret && flags == GFP_KERNEL) {
709                 struct mem_cgroup *memcg, *old_memcg;
710
711                 memcg = get_memcg(c);
712                 old_memcg = set_active_memcg(memcg);
713                 ret = __alloc(c, NUMA_NO_NODE, GFP_KERNEL | __GFP_NOWARN | __GFP_ACCOUNT);
714                 set_active_memcg(old_memcg);
715                 mem_cgroup_put(memcg);
716         }
717
718         return !ret ? NULL : ret + LLIST_NODE_SZ;
719 }