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