xref: /linux/kernel/bpf/memalloc.c (revision fbd97dd1d3ce32d32fb7be86acc3fdb7c04fa043)
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 #define BPF_MEM_ALLOC_SIZE_MAX 4096
39 
40 /* similar to kmalloc, but sizeof == 8 bucket is gone */
41 static u8 size_index[24] __ro_after_init = {
42 	3,	/* 8 */
43 	3,	/* 16 */
44 	4,	/* 24 */
45 	4,	/* 32 */
46 	5,	/* 40 */
47 	5,	/* 48 */
48 	5,	/* 56 */
49 	5,	/* 64 */
50 	1,	/* 72 */
51 	1,	/* 80 */
52 	1,	/* 88 */
53 	1,	/* 96 */
54 	6,	/* 104 */
55 	6,	/* 112 */
56 	6,	/* 120 */
57 	6,	/* 128 */
58 	2,	/* 136 */
59 	2,	/* 144 */
60 	2,	/* 152 */
61 	2,	/* 160 */
62 	2,	/* 168 */
63 	2,	/* 176 */
64 	2,	/* 184 */
65 	2	/* 192 */
66 };
67 
68 static int bpf_mem_cache_idx(size_t size)
69 {
70 	if (!size || size > BPF_MEM_ALLOC_SIZE_MAX)
71 		return -1;
72 
73 	if (size <= 192)
74 		return size_index[(size - 1) / 8] - 1;
75 
76 	return fls(size - 1) - 2;
77 }
78 
79 #define NUM_CACHES 11
80 
81 struct bpf_mem_cache {
82 	/* per-cpu list of free objects of size 'unit_size'.
83 	 * All accesses are done with interrupts disabled and 'active' counter
84 	 * protection with __llist_add() and __llist_del_first().
85 	 */
86 	struct llist_head free_llist;
87 	local_t active;
88 
89 	/* Operations on the free_list from unit_alloc/unit_free/bpf_mem_refill
90 	 * are sequenced by per-cpu 'active' counter. But unit_free() cannot
91 	 * fail. When 'active' is busy the unit_free() will add an object to
92 	 * free_llist_extra.
93 	 */
94 	struct llist_head free_llist_extra;
95 
96 	struct irq_work refill_work;
97 	struct obj_cgroup *objcg;
98 	int unit_size;
99 	/* count of objects in free_llist */
100 	int free_cnt;
101 	int low_watermark, high_watermark, batch;
102 	int percpu_size;
103 	bool draining;
104 	struct bpf_mem_cache *tgt;
105 	void (*dtor)(void *obj, void *ctx);
106 	void *dtor_ctx;
107 
108 	/* list of objects to be freed after RCU GP */
109 	struct llist_head free_by_rcu;
110 	struct llist_node *free_by_rcu_tail;
111 	struct llist_head waiting_for_gp;
112 	struct llist_node *waiting_for_gp_tail;
113 	struct rcu_head rcu;
114 	atomic_t call_rcu_in_progress;
115 	struct llist_head free_llist_extra_rcu;
116 
117 	/* list of objects to be freed after RCU tasks trace GP */
118 	struct llist_head free_by_rcu_ttrace;
119 	struct llist_head waiting_for_gp_ttrace;
120 	struct rcu_head rcu_ttrace;
121 	/*
122 	 * 0 - idle
123 	 * 1 - __free_rcu() is queued
124 	 * 2 - __free_rcu() is queued and free_by_rcu_ttrace got more objects since
125 	 */
126 	atomic_t call_rcu_ttrace_in_progress;
127 	raw_spinlock_t lock;
128 };
129 
130 struct bpf_mem_caches {
131 	struct bpf_mem_cache cache[NUM_CACHES];
132 };
133 
134 static const u16 sizes[NUM_CACHES] = {96, 192, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096};
135 
136 static struct llist_node notrace *__llist_del_first(struct llist_head *head)
137 {
138 	struct llist_node *entry, *next;
139 
140 	entry = head->first;
141 	if (!entry)
142 		return NULL;
143 	next = entry->next;
144 	head->first = next;
145 	return entry;
146 }
147 
148 static void *__alloc(struct bpf_mem_cache *c, int node, gfp_t flags)
149 {
150 	if (c->percpu_size) {
151 		void __percpu **obj = kmalloc_node(c->percpu_size, flags, node);
152 		void __percpu *pptr = __alloc_percpu_gfp(c->unit_size, 8, flags);
153 
154 		if (!obj || !pptr) {
155 			free_percpu(pptr);
156 			kfree(obj);
157 			return NULL;
158 		}
159 		obj[1] = pptr;
160 		return obj;
161 	}
162 
163 	return kmalloc_node(c->unit_size, flags | __GFP_ZERO, node);
164 }
165 
166 static struct mem_cgroup *get_memcg(const struct bpf_mem_cache *c)
167 {
168 #ifdef CONFIG_MEMCG
169 	if (c->objcg)
170 		return get_mem_cgroup_from_objcg(c->objcg);
171 	return root_mem_cgroup;
172 #else
173 	return NULL;
174 #endif
175 }
176 
177 static void inc_active(struct bpf_mem_cache *c, unsigned long *flags)
178 {
179 	if (IS_ENABLED(CONFIG_PREEMPT_RT))
180 		/* In RT irq_work runs in per-cpu kthread, so disable
181 		 * interrupts to avoid preemption and interrupts and
182 		 * reduce the chance of bpf prog executing on this cpu
183 		 * when active counter is busy.
184 		 */
185 		local_irq_save(*flags);
186 	/* alloc_bulk runs from irq_work which will not preempt a bpf
187 	 * program that does unit_alloc/unit_free since IRQs are
188 	 * disabled there. There is no race to increment 'active'
189 	 * counter. It protects free_llist from corruption in case NMI
190 	 * bpf prog preempted this loop.
191 	 */
192 	WARN_ON_ONCE(local_inc_return(&c->active) != 1);
193 }
194 
195 static void dec_active(struct bpf_mem_cache *c, unsigned long *flags)
196 {
197 	local_dec(&c->active);
198 	if (IS_ENABLED(CONFIG_PREEMPT_RT))
199 		local_irq_restore(*flags);
200 }
201 
202 static void add_obj_to_free_list(struct bpf_mem_cache *c, void *obj)
203 {
204 	unsigned long flags;
205 
206 	inc_active(c, &flags);
207 	__llist_add(obj, &c->free_llist);
208 	c->free_cnt++;
209 	dec_active(c, &flags);
210 }
211 
212 /* Mostly runs from irq_work except __init phase. */
213 static void alloc_bulk(struct bpf_mem_cache *c, int cnt, int node, bool atomic)
214 {
215 	struct mem_cgroup *memcg = NULL, *old_memcg;
216 	gfp_t gfp;
217 	void *obj;
218 	int i;
219 
220 	gfp = __GFP_NOWARN | __GFP_ACCOUNT;
221 	gfp |= atomic ? GFP_NOWAIT : GFP_KERNEL;
222 
223 	/*
224 	 * c->lock serializes concurrent llist_del_first() against
225 	 * llist_del_all() in __free_rcu() and do_call_rcu_ttrace().
226 	 */
227 	scoped_guard(raw_spinlock_irqsave, &c->lock) {
228 		for (i = 0; i < cnt; i++) {
229 			obj = llist_del_first(&c->free_by_rcu_ttrace);
230 			if (!obj)
231 				break;
232 			add_obj_to_free_list(c, obj);
233 		}
234 
235 		for (; i < cnt; i++) {
236 			obj = llist_del_first(&c->waiting_for_gp_ttrace);
237 			if (!obj)
238 				break;
239 			add_obj_to_free_list(c, obj);
240 		}
241 	}
242 	if (i >= cnt)
243 		return;
244 
245 	memcg = get_memcg(c);
246 	old_memcg = set_active_memcg(memcg);
247 	for (; i < cnt; i++) {
248 		/* Allocate, but don't deplete atomic reserves that typical
249 		 * GFP_ATOMIC would do. irq_work runs on this cpu and kmalloc
250 		 * will allocate from the current numa node which is what we
251 		 * want here.
252 		 */
253 		obj = __alloc(c, node, gfp);
254 		if (!obj)
255 			break;
256 		add_obj_to_free_list(c, obj);
257 	}
258 	set_active_memcg(old_memcg);
259 	mem_cgroup_put(memcg);
260 }
261 
262 static void free_one(void *obj, bool percpu)
263 {
264 	if (percpu)
265 		free_percpu(((void __percpu **)obj)[1]);
266 
267 	kfree(obj);
268 }
269 
270 static int free_all(struct bpf_mem_cache *c, struct llist_node *llnode, bool percpu)
271 {
272 	struct llist_node *pos, *t;
273 	int cnt = 0;
274 
275 	llist_for_each_safe(pos, t, llnode) {
276 		if (c->dtor)
277 			c->dtor((void *)pos + LLIST_NODE_SZ, c->dtor_ctx);
278 		free_one(pos, percpu);
279 		cnt++;
280 	}
281 	return cnt;
282 }
283 
284 static void __do_call_rcu_ttrace(struct bpf_mem_cache *c);
285 
286 static void __free_rcu(struct rcu_head *head)
287 {
288 	struct bpf_mem_cache *c = container_of(head, struct bpf_mem_cache, rcu_ttrace);
289 	struct llist_node *llnode;
290 
291 	scoped_guard(raw_spinlock_irqsave, &c->lock)
292 		llnode = llist_del_all(&c->waiting_for_gp_ttrace);
293 
294 	free_all(c, llnode, !!c->percpu_size);
295 
296 	/*
297 	 * do_call_rcu_ttrace() that ran while GP was in flight left its objects
298 	 * in free_by_rcu_ttrace. This cache may never free or alloc in bulk
299 	 * again, so start the next GP from here.
300 	 * 'c' can be freed as soon as call_rcu_ttrace_in_progress is zero.
301 	 */
302 	if (atomic_cmpxchg(&c->call_rcu_ttrace_in_progress, 1, 0) == 1)
303 		return;
304 
305 	/* Pairs with synchronize_rcu() in free_mem_alloc() */
306 	guard(rcu)();
307 	__do_call_rcu_ttrace(c);
308 }
309 
310 static void enque_to_free(struct bpf_mem_cache *c, void *obj)
311 {
312 	struct llist_node *llnode = obj;
313 
314 	/* bpf_mem_cache is a per-cpu object. Freeing happens in irq_work.
315 	 * Nothing races to add to free_by_rcu_ttrace list.
316 	 */
317 	llist_add(llnode, &c->free_by_rcu_ttrace);
318 }
319 
320 static void __do_call_rcu_ttrace(struct bpf_mem_cache *c)
321 {
322 	struct llist_node *llnode, *t;
323 
324 	/*
325 	 * Must be done before llist_del_all(). Objects that it misses were
326 	 * added by do_call_rcu_ttrace() that will set 2 after this store.
327 	 */
328 	atomic_set(&c->call_rcu_ttrace_in_progress, 1);
329 
330 	WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp_ttrace));
331 	llist_for_each_safe(llnode, t, llist_del_all(&c->free_by_rcu_ttrace))
332 		llist_add(llnode, &c->waiting_for_gp_ttrace);
333 
334 	if (unlikely(READ_ONCE(c->draining))) {
335 		__free_rcu(&c->rcu_ttrace);
336 		return;
337 	}
338 
339 	/*
340 	 * Use call_rcu_tasks_trace() to wait for sleepable progs to finish.
341 	 * RCU Tasks Trace grace period implies RCU grace period, so pass
342 	 * __free_rcu directly as the callback.
343 	 */
344 	call_rcu_tasks_trace(&c->rcu_ttrace, __free_rcu);
345 }
346 
347 static void do_call_rcu_ttrace(struct bpf_mem_cache *c)
348 {
349 	struct llist_node *llnode;
350 
351 	if (atomic_xchg(&c->call_rcu_ttrace_in_progress, 2)) {
352 		if (unlikely(READ_ONCE(c->draining))) {
353 			scoped_guard(raw_spinlock_irqsave, &c->lock)
354 				llnode = llist_del_all(&c->free_by_rcu_ttrace);
355 			free_all(c, llnode, !!c->percpu_size);
356 		}
357 		return;
358 	}
359 
360 	__do_call_rcu_ttrace(c);
361 }
362 
363 static void free_bulk(struct bpf_mem_cache *c)
364 {
365 	struct bpf_mem_cache *tgt = c->tgt;
366 	struct llist_node *llnode, *t;
367 	unsigned long flags;
368 	int cnt;
369 
370 	WARN_ON_ONCE(tgt->unit_size != c->unit_size);
371 	WARN_ON_ONCE(tgt->percpu_size != c->percpu_size);
372 
373 	do {
374 		inc_active(c, &flags);
375 		llnode = __llist_del_first(&c->free_llist);
376 		if (llnode)
377 			cnt = --c->free_cnt;
378 		else
379 			cnt = 0;
380 		dec_active(c, &flags);
381 		if (llnode)
382 			enque_to_free(tgt, llnode);
383 	} while (cnt > (c->high_watermark + c->low_watermark) / 2);
384 
385 	/* and drain free_llist_extra */
386 	llist_for_each_safe(llnode, t, llist_del_all(&c->free_llist_extra))
387 		enque_to_free(tgt, llnode);
388 	do_call_rcu_ttrace(tgt);
389 }
390 
391 static void __free_by_rcu(struct rcu_head *head)
392 {
393 	struct bpf_mem_cache *c = container_of(head, struct bpf_mem_cache, rcu);
394 	struct bpf_mem_cache *tgt = c->tgt;
395 	struct llist_node *llnode;
396 
397 	WARN_ON_ONCE(tgt->unit_size != c->unit_size);
398 	WARN_ON_ONCE(tgt->percpu_size != c->percpu_size);
399 
400 	llnode = llist_del_all(&c->waiting_for_gp);
401 	if (!llnode)
402 		goto out;
403 
404 	llist_add_batch(llnode, c->waiting_for_gp_tail, &tgt->free_by_rcu_ttrace);
405 
406 	/* Objects went through regular RCU GP. Send them to RCU tasks trace */
407 	do_call_rcu_ttrace(tgt);
408 out:
409 	atomic_set(&c->call_rcu_in_progress, 0);
410 }
411 
412 static void check_free_by_rcu(struct bpf_mem_cache *c)
413 {
414 	struct llist_node *llnode, *t;
415 	unsigned long flags;
416 
417 	/* drain free_llist_extra_rcu */
418 	if (unlikely(!llist_empty(&c->free_llist_extra_rcu))) {
419 		inc_active(c, &flags);
420 		llist_for_each_safe(llnode, t, llist_del_all(&c->free_llist_extra_rcu))
421 			if (__llist_add(llnode, &c->free_by_rcu))
422 				c->free_by_rcu_tail = llnode;
423 		dec_active(c, &flags);
424 	}
425 
426 	if (llist_empty(&c->free_by_rcu))
427 		return;
428 
429 	if (atomic_xchg(&c->call_rcu_in_progress, 1)) {
430 		/*
431 		 * Instead of kmalloc-ing new rcu_head and triggering 10k
432 		 * call_rcu() to hit rcutree.qhimark and force RCU to notice
433 		 * the overload just ask RCU to hurry up. There could be many
434 		 * objects in free_by_rcu list.
435 		 * This hint reduces memory consumption for an artificial
436 		 * benchmark from 2 Gbyte to 150 Mbyte.
437 		 */
438 		rcu_request_urgent_qs_task(current);
439 		return;
440 	}
441 
442 	WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp));
443 
444 	inc_active(c, &flags);
445 	WRITE_ONCE(c->waiting_for_gp.first, __llist_del_all(&c->free_by_rcu));
446 	c->waiting_for_gp_tail = c->free_by_rcu_tail;
447 	dec_active(c, &flags);
448 
449 	if (unlikely(READ_ONCE(c->draining))) {
450 		free_all(c, llist_del_all(&c->waiting_for_gp), !!c->percpu_size);
451 		atomic_set(&c->call_rcu_in_progress, 0);
452 	} else {
453 		call_rcu_hurry(&c->rcu, __free_by_rcu);
454 	}
455 }
456 
457 static void bpf_mem_refill(struct irq_work *work)
458 {
459 	struct bpf_mem_cache *c = container_of(work, struct bpf_mem_cache, refill_work);
460 	int cnt;
461 
462 	/* Racy access to free_cnt. It doesn't need to be 100% accurate */
463 	cnt = c->free_cnt;
464 	if (cnt < c->low_watermark)
465 		/* irq_work runs on this cpu and kmalloc will allocate
466 		 * from the current numa node which is what we want here.
467 		 */
468 		alloc_bulk(c, c->batch, NUMA_NO_NODE, true);
469 	else if (cnt > c->high_watermark)
470 		free_bulk(c);
471 
472 	check_free_by_rcu(c);
473 }
474 
475 static void notrace irq_work_raise(struct bpf_mem_cache *c)
476 {
477 	irq_work_queue(&c->refill_work);
478 }
479 
480 /* For typical bpf map case that uses bpf_mem_cache_alloc and single bucket
481  * the freelist cache will be elem_size * 64 (or less) on each cpu.
482  *
483  * For bpf programs that don't have statically known allocation sizes and
484  * assuming (low_mark + high_mark) / 2 as an average number of elements per
485  * bucket and all buckets are used the total amount of memory in freelists
486  * on each cpu will be:
487  * 64*16 + 64*32 + 64*64 + 64*96 + 64*128 + 64*196 + 64*256 + 32*512 + 16*1024 + 8*2048 + 4*4096
488  * == ~ 116 Kbyte using below heuristic.
489  * Initialized, but unused bpf allocator (not bpf map specific one) will
490  * consume ~ 11 Kbyte per cpu.
491  * Typical case will be between 11K and 116K closer to 11K.
492  * bpf progs can and should share bpf_mem_cache when possible.
493  *
494  * Percpu allocation is typically rare. To avoid potential unnecessary large
495  * memory consumption, set low_mark = 1 and high_mark = 3, resulting in c->batch = 1.
496  */
497 static void init_refill_work(struct bpf_mem_cache *c)
498 {
499 	init_irq_work(&c->refill_work, bpf_mem_refill);
500 	if (c->percpu_size) {
501 		c->low_watermark = 1;
502 		c->high_watermark = 3;
503 	} else if (c->unit_size <= 256) {
504 		c->low_watermark = 32;
505 		c->high_watermark = 96;
506 	} else {
507 		/* When page_size == 4k, order-0 cache will have low_mark == 2
508 		 * and high_mark == 6 with batch alloc of 3 individual pages at
509 		 * a time.
510 		 * 8k allocs and above low == 1, high == 3, batch == 1.
511 		 */
512 		c->low_watermark = max(32 * 256 / c->unit_size, 1);
513 		c->high_watermark = max(96 * 256 / c->unit_size, 3);
514 	}
515 	c->batch = max((c->high_watermark - c->low_watermark) / 4 * 3, 1);
516 }
517 
518 static void prefill_mem_cache(struct bpf_mem_cache *c, int cpu)
519 {
520 	int cnt = 1;
521 
522 	/* To avoid consuming memory, for non-percpu allocation, assume that
523 	 * 1st run of bpf prog won't be doing more than 4 map_update_elem from
524 	 * irq disabled region if unit size is less than or equal to 256.
525 	 * For all other cases, let us just do one allocation.
526 	 */
527 	if (!c->percpu_size && c->unit_size <= 256)
528 		cnt = 4;
529 	alloc_bulk(c, cnt, cpu_to_node(cpu), false);
530 }
531 
532 /* When size != 0 bpf_mem_cache for each cpu.
533  * This is typical bpf hash map use case when all elements have equal size.
534  *
535  * When size == 0 allocate 11 bpf_mem_cache-s for each cpu, then rely on
536  * kmalloc/kfree. Max allocation size is 4096 in this case.
537  * This is bpf_dynptr and bpf_kptr use case.
538  */
539 int bpf_mem_alloc_init(struct bpf_mem_alloc *ma, int size, bool percpu)
540 {
541 	struct bpf_mem_caches *cc; struct bpf_mem_caches __percpu *pcc;
542 	struct bpf_mem_cache *c; struct bpf_mem_cache __percpu *pc;
543 	struct obj_cgroup *objcg = NULL;
544 	int cpu, i, unit_size, percpu_size = 0;
545 
546 	if (percpu && size == 0)
547 		return -EINVAL;
548 
549 	/* room for llist_node and per-cpu pointer */
550 	if (percpu)
551 		percpu_size = LLIST_NODE_SZ + sizeof(void *);
552 	ma->percpu = percpu;
553 
554 	if (size) {
555 		pc = __alloc_percpu_gfp(sizeof(*pc), 8, GFP_KERNEL);
556 		if (!pc)
557 			return -ENOMEM;
558 
559 		if (!percpu)
560 			size += LLIST_NODE_SZ; /* room for llist_node */
561 		unit_size = size;
562 
563 #ifdef CONFIG_MEMCG
564 		if (memcg_bpf_enabled())
565 			objcg = get_obj_cgroup_from_current();
566 #endif
567 		ma->objcg = objcg;
568 
569 		for_each_possible_cpu(cpu) {
570 			c = per_cpu_ptr(pc, cpu);
571 			c->unit_size = unit_size;
572 			c->objcg = objcg;
573 			c->percpu_size = percpu_size;
574 			c->tgt = c;
575 			raw_spin_lock_init(&c->lock);
576 			init_refill_work(c);
577 			prefill_mem_cache(c, cpu);
578 		}
579 		ma->cache = pc;
580 		return 0;
581 	}
582 
583 	pcc = __alloc_percpu_gfp(sizeof(*cc), 8, GFP_KERNEL);
584 	if (!pcc)
585 		return -ENOMEM;
586 #ifdef CONFIG_MEMCG
587 	objcg = get_obj_cgroup_from_current();
588 #endif
589 	ma->objcg = objcg;
590 	for_each_possible_cpu(cpu) {
591 		cc = per_cpu_ptr(pcc, cpu);
592 		for (i = 0; i < NUM_CACHES; i++) {
593 			c = &cc->cache[i];
594 			c->unit_size = sizes[i];
595 			c->objcg = objcg;
596 			c->percpu_size = percpu_size;
597 			c->tgt = c;
598 			raw_spin_lock_init(&c->lock);
599 			init_refill_work(c);
600 			prefill_mem_cache(c, cpu);
601 		}
602 	}
603 
604 	ma->caches = pcc;
605 	return 0;
606 }
607 
608 int bpf_mem_alloc_percpu_init(struct bpf_mem_alloc *ma, struct obj_cgroup *objcg)
609 {
610 	struct bpf_mem_caches __percpu *pcc;
611 
612 	pcc = __alloc_percpu_gfp(sizeof(struct bpf_mem_caches), 8, GFP_KERNEL);
613 	if (!pcc)
614 		return -ENOMEM;
615 
616 	ma->caches = pcc;
617 	ma->objcg = objcg;
618 	ma->percpu = true;
619 	return 0;
620 }
621 
622 int bpf_mem_alloc_percpu_unit_init(struct bpf_mem_alloc *ma, int size)
623 {
624 	struct bpf_mem_caches *cc; struct bpf_mem_caches __percpu *pcc;
625 	int cpu, i, unit_size, percpu_size;
626 	struct obj_cgroup *objcg;
627 	struct bpf_mem_cache *c;
628 
629 	i = bpf_mem_cache_idx(size);
630 	if (i < 0)
631 		return -EINVAL;
632 
633 	/* room for llist_node and per-cpu pointer */
634 	percpu_size = LLIST_NODE_SZ + sizeof(void *);
635 
636 	unit_size = sizes[i];
637 	objcg = ma->objcg;
638 	pcc = ma->caches;
639 
640 	for_each_possible_cpu(cpu) {
641 		cc = per_cpu_ptr(pcc, cpu);
642 		c = &cc->cache[i];
643 		if (c->unit_size)
644 			break;
645 
646 		c->unit_size = unit_size;
647 		c->objcg = objcg;
648 		c->percpu_size = percpu_size;
649 		c->tgt = c;
650 		raw_spin_lock_init(&c->lock);
651 		init_refill_work(c);
652 		prefill_mem_cache(c, cpu);
653 	}
654 
655 	return 0;
656 }
657 
658 static void drain_mem_cache(struct bpf_mem_cache *c)
659 {
660 	bool percpu = !!c->percpu_size;
661 
662 	/* No progs are using this bpf_mem_cache, but htab_map_free() called
663 	 * bpf_mem_cache_free() for all remaining elements and they can be in
664 	 * free_by_rcu_ttrace or in waiting_for_gp_ttrace lists, so drain those lists now.
665 	 *
666 	 * Except for waiting_for_gp_ttrace list, there are no concurrent operations
667 	 * on these lists, so it is safe to use __llist_del_all().
668 	 */
669 	free_all(c, llist_del_all(&c->free_by_rcu_ttrace), percpu);
670 	free_all(c, llist_del_all(&c->waiting_for_gp_ttrace), percpu);
671 	free_all(c, __llist_del_all(&c->free_llist), percpu);
672 	free_all(c, __llist_del_all(&c->free_llist_extra), percpu);
673 	free_all(c, __llist_del_all(&c->free_by_rcu), percpu);
674 	free_all(c, __llist_del_all(&c->free_llist_extra_rcu), percpu);
675 	free_all(c, llist_del_all(&c->waiting_for_gp), percpu);
676 }
677 
678 static void check_mem_cache(struct bpf_mem_cache *c)
679 {
680 	WARN_ON_ONCE(!llist_empty(&c->free_by_rcu_ttrace));
681 	WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp_ttrace));
682 	WARN_ON_ONCE(!llist_empty(&c->free_llist));
683 	WARN_ON_ONCE(!llist_empty(&c->free_llist_extra));
684 	WARN_ON_ONCE(!llist_empty(&c->free_by_rcu));
685 	WARN_ON_ONCE(!llist_empty(&c->free_llist_extra_rcu));
686 	WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp));
687 }
688 
689 static void check_leaked_objs(struct bpf_mem_alloc *ma)
690 {
691 	struct bpf_mem_caches *cc;
692 	struct bpf_mem_cache *c;
693 	int cpu, i;
694 
695 	if (ma->cache) {
696 		for_each_possible_cpu(cpu) {
697 			c = per_cpu_ptr(ma->cache, cpu);
698 			check_mem_cache(c);
699 		}
700 	}
701 	if (ma->caches) {
702 		for_each_possible_cpu(cpu) {
703 			cc = per_cpu_ptr(ma->caches, cpu);
704 			for (i = 0; i < NUM_CACHES; i++) {
705 				c = &cc->cache[i];
706 				check_mem_cache(c);
707 			}
708 		}
709 	}
710 }
711 
712 static void free_mem_alloc_no_barrier(struct bpf_mem_alloc *ma)
713 {
714 	/* We can free dtor ctx only once all callbacks are done using it. */
715 	if (ma->dtor_ctx_free)
716 		ma->dtor_ctx_free(ma->dtor_ctx);
717 	check_leaked_objs(ma);
718 	free_percpu(ma->cache);
719 	free_percpu(ma->caches);
720 	ma->cache = NULL;
721 	ma->caches = NULL;
722 }
723 
724 static void free_mem_alloc(struct bpf_mem_alloc *ma)
725 {
726 	/*
727 	 * waiting_for_gp[_ttrace] lists were drained, but RCU callbacks
728 	 * might still execute. Wait for them.
729 	 *
730 	 * rcu_barrier_tasks_trace() doesn't imply synchronize_rcu_tasks_trace(),
731 	 * but rcu_barrier_tasks_trace() and rcu_barrier() below are only used
732 	 * to wait for the pending __free_by_rcu(), and __free_rcu(). RCU Tasks
733 	 * Trace grace period implies RCU grace period, so all __free_rcu don't
734 	 * need extra call_rcu() (and thus extra rcu_barrier() here).
735 	 *
736 	 * __free_rcu() queues itself again unless it sees 'draining'. After
737 	 * synchronize_rcu() it either did that already or will not do it, so
738 	 * rcu_barrier_tasks_trace() cannot miss it.
739 	 */
740 	synchronize_rcu();
741 	rcu_barrier(); /* wait for __free_by_rcu */
742 	rcu_barrier_tasks_trace(); /* wait for __free_rcu */
743 	free_mem_alloc_no_barrier(ma);
744 }
745 
746 static void free_mem_alloc_deferred(struct work_struct *work)
747 {
748 	struct bpf_mem_alloc *ma = container_of(work, struct bpf_mem_alloc, work);
749 
750 	free_mem_alloc(ma);
751 	kfree(ma);
752 }
753 
754 static void destroy_mem_alloc(struct bpf_mem_alloc *ma, int rcu_in_progress)
755 {
756 	struct bpf_mem_alloc *copy;
757 
758 	if (!rcu_in_progress) {
759 		/* Fast path. No callbacks are pending, hence no need to do
760 		 * rcu_barrier-s.
761 		 */
762 		free_mem_alloc_no_barrier(ma);
763 		return;
764 	}
765 
766 	copy = kmemdup(ma, sizeof(*ma), GFP_KERNEL);
767 	if (!copy) {
768 		/* Slow path with inline barrier-s */
769 		free_mem_alloc(ma);
770 		return;
771 	}
772 
773 	/* Defer barriers into worker to let the rest of map memory to be freed */
774 	memset(ma, 0, sizeof(*ma));
775 	INIT_WORK(&copy->work, free_mem_alloc_deferred);
776 	queue_work(system_dfl_wq, &copy->work);
777 }
778 
779 void bpf_mem_alloc_destroy(struct bpf_mem_alloc *ma)
780 {
781 	struct bpf_mem_caches *cc;
782 	struct bpf_mem_cache *c;
783 	int cpu, i, rcu_in_progress;
784 
785 	if (ma->cache) {
786 		rcu_in_progress = 0;
787 		for_each_possible_cpu(cpu) {
788 			c = per_cpu_ptr(ma->cache, cpu);
789 			WRITE_ONCE(c->draining, true);
790 			irq_work_sync(&c->refill_work);
791 			drain_mem_cache(c);
792 			rcu_in_progress += atomic_read(&c->call_rcu_ttrace_in_progress);
793 			rcu_in_progress += atomic_read(&c->call_rcu_in_progress);
794 		}
795 		obj_cgroup_put(ma->objcg);
796 		destroy_mem_alloc(ma, rcu_in_progress);
797 	}
798 	if (ma->caches) {
799 		rcu_in_progress = 0;
800 		for_each_possible_cpu(cpu) {
801 			cc = per_cpu_ptr(ma->caches, cpu);
802 			for (i = 0; i < NUM_CACHES; i++) {
803 				c = &cc->cache[i];
804 				WRITE_ONCE(c->draining, true);
805 				irq_work_sync(&c->refill_work);
806 				drain_mem_cache(c);
807 				rcu_in_progress += atomic_read(&c->call_rcu_ttrace_in_progress);
808 				rcu_in_progress += atomic_read(&c->call_rcu_in_progress);
809 			}
810 		}
811 		obj_cgroup_put(ma->objcg);
812 		destroy_mem_alloc(ma, rcu_in_progress);
813 	}
814 }
815 
816 /* notrace is necessary here and in other functions to make sure
817  * bpf programs cannot attach to them and cause llist corruptions.
818  */
819 static void notrace *unit_alloc(struct bpf_mem_cache *c)
820 {
821 	struct llist_node *llnode = NULL;
822 	unsigned long flags;
823 	int cnt = 0;
824 
825 	/* Disable irqs to prevent the following race for majority of prog types:
826 	 * prog_A
827 	 *   bpf_mem_alloc
828 	 *      preemption or irq -> prog_B
829 	 *        bpf_mem_alloc
830 	 *
831 	 * but prog_B could be a perf_event NMI prog.
832 	 * Use per-cpu 'active' counter to order free_list access between
833 	 * unit_alloc/unit_free/bpf_mem_refill.
834 	 */
835 	local_irq_save(flags);
836 	if (local_inc_return(&c->active) == 1) {
837 		llnode = __llist_del_first(&c->free_llist);
838 		if (llnode) {
839 			cnt = --c->free_cnt;
840 			*(struct bpf_mem_cache **)llnode = c;
841 		}
842 	}
843 	local_dec(&c->active);
844 
845 	WARN_ON(cnt < 0);
846 
847 	if (cnt < c->low_watermark)
848 		irq_work_raise(c);
849 	/* Enable IRQ after the enqueue of irq work completes, so irq work
850 	 * will run after IRQ is enabled and free_llist may be refilled by
851 	 * irq work before other task preempts current task.
852 	 */
853 	local_irq_restore(flags);
854 
855 	return llnode;
856 }
857 
858 /* Though 'ptr' object could have been allocated on a different cpu
859  * add it to the free_llist of the current cpu.
860  * Let kfree() logic deal with it when it's later called from irq_work.
861  */
862 static void notrace unit_free(struct bpf_mem_cache *c, void *ptr)
863 {
864 	struct llist_node *llnode = ptr - LLIST_NODE_SZ;
865 	unsigned long flags;
866 	int cnt = 0;
867 
868 	BUILD_BUG_ON(LLIST_NODE_SZ > 8);
869 
870 	/*
871 	 * Remember bpf_mem_cache that allocated this object.
872 	 * The hint is not accurate.
873 	 */
874 	c->tgt = *(struct bpf_mem_cache **)llnode;
875 
876 	local_irq_save(flags);
877 	if (local_inc_return(&c->active) == 1) {
878 		__llist_add(llnode, &c->free_llist);
879 		cnt = ++c->free_cnt;
880 	} else {
881 		/* unit_free() cannot fail. Therefore add an object to atomic
882 		 * llist. free_bulk() will drain it. Though free_llist_extra is
883 		 * a per-cpu list we have to use atomic llist_add here, since
884 		 * it also can be interrupted by bpf nmi prog that does another
885 		 * unit_free() into the same free_llist_extra.
886 		 */
887 		llist_add(llnode, &c->free_llist_extra);
888 	}
889 	local_dec(&c->active);
890 
891 	if (cnt > c->high_watermark)
892 		/* free few objects from current cpu into global kmalloc pool */
893 		irq_work_raise(c);
894 	/* Enable IRQ after irq_work_raise() completes, otherwise when current
895 	 * task is preempted by task which does unit_alloc(), unit_alloc() may
896 	 * return NULL unexpectedly because irq work is already pending but can
897 	 * not been triggered and free_llist can not be refilled timely.
898 	 */
899 	local_irq_restore(flags);
900 }
901 
902 static void notrace unit_free_rcu(struct bpf_mem_cache *c, void *ptr)
903 {
904 	struct llist_node *llnode = ptr - LLIST_NODE_SZ;
905 	unsigned long flags;
906 
907 	c->tgt = *(struct bpf_mem_cache **)llnode;
908 
909 	local_irq_save(flags);
910 	if (local_inc_return(&c->active) == 1) {
911 		if (__llist_add(llnode, &c->free_by_rcu))
912 			c->free_by_rcu_tail = llnode;
913 	} else {
914 		llist_add(llnode, &c->free_llist_extra_rcu);
915 	}
916 	local_dec(&c->active);
917 
918 	if (!atomic_read(&c->call_rcu_in_progress))
919 		irq_work_raise(c);
920 	local_irq_restore(flags);
921 }
922 
923 /* Called from BPF program or from sys_bpf syscall.
924  * In both cases migration is disabled.
925  */
926 void notrace *bpf_mem_alloc(struct bpf_mem_alloc *ma, size_t size)
927 {
928 	int idx;
929 	void *ret;
930 
931 	if (!size)
932 		return NULL;
933 
934 	if (!ma->percpu)
935 		size += LLIST_NODE_SZ;
936 	idx = bpf_mem_cache_idx(size);
937 	if (idx < 0)
938 		return NULL;
939 
940 	ret = unit_alloc(this_cpu_ptr(ma->caches)->cache + idx);
941 	return !ret ? NULL : ret + LLIST_NODE_SZ;
942 }
943 
944 void notrace bpf_mem_free(struct bpf_mem_alloc *ma, void *ptr)
945 {
946 	struct bpf_mem_cache *c;
947 	int idx;
948 
949 	if (!ptr)
950 		return;
951 
952 	c = *(void **)(ptr - LLIST_NODE_SZ);
953 	idx = bpf_mem_cache_idx(c->unit_size);
954 	if (WARN_ON_ONCE(idx < 0))
955 		return;
956 
957 	unit_free(this_cpu_ptr(ma->caches)->cache + idx, ptr);
958 }
959 
960 void notrace bpf_mem_free_rcu(struct bpf_mem_alloc *ma, void *ptr)
961 {
962 	struct bpf_mem_cache *c;
963 	int idx;
964 
965 	if (!ptr)
966 		return;
967 
968 	c = *(void **)(ptr - LLIST_NODE_SZ);
969 	idx = bpf_mem_cache_idx(c->unit_size);
970 	if (WARN_ON_ONCE(idx < 0))
971 		return;
972 
973 	unit_free_rcu(this_cpu_ptr(ma->caches)->cache + idx, ptr);
974 }
975 
976 void notrace *bpf_mem_cache_alloc(struct bpf_mem_alloc *ma)
977 {
978 	void *ret;
979 
980 	ret = unit_alloc(this_cpu_ptr(ma->cache));
981 	return !ret ? NULL : ret + LLIST_NODE_SZ;
982 }
983 
984 void notrace bpf_mem_cache_free(struct bpf_mem_alloc *ma, void *ptr)
985 {
986 	if (!ptr)
987 		return;
988 
989 	unit_free(this_cpu_ptr(ma->cache), ptr);
990 }
991 
992 void notrace bpf_mem_cache_free_rcu(struct bpf_mem_alloc *ma, void *ptr)
993 {
994 	if (!ptr)
995 		return;
996 
997 	unit_free_rcu(this_cpu_ptr(ma->cache), ptr);
998 }
999 
1000 /* Directly does a kfree() without putting 'ptr' back to the free_llist
1001  * for reuse and without waiting for a rcu_tasks_trace gp.
1002  * The caller must first go through the rcu_tasks_trace gp for 'ptr'
1003  * before calling bpf_mem_cache_raw_free().
1004  * It could be used when the rcu_tasks_trace callback does not have
1005  * a hold on the original bpf_mem_alloc object that allocated the
1006  * 'ptr'. This should only be used in the uncommon code path.
1007  * Otherwise, the bpf_mem_alloc's free_llist cannot be refilled
1008  * and may affect performance.
1009  */
1010 void bpf_mem_cache_raw_free(void *ptr)
1011 {
1012 	if (!ptr)
1013 		return;
1014 
1015 	kfree(ptr - LLIST_NODE_SZ);
1016 }
1017 
1018 /* When flags == GFP_KERNEL, it signals that the caller will not cause
1019  * deadlock when using kmalloc. bpf_mem_cache_alloc_flags() will use
1020  * kmalloc if the free_llist is empty.
1021  */
1022 void notrace *bpf_mem_cache_alloc_flags(struct bpf_mem_alloc *ma, gfp_t flags)
1023 {
1024 	struct bpf_mem_cache *c;
1025 	void *ret;
1026 
1027 	c = this_cpu_ptr(ma->cache);
1028 
1029 	ret = unit_alloc(c);
1030 	if (!ret && flags == GFP_KERNEL) {
1031 		struct mem_cgroup *memcg, *old_memcg;
1032 
1033 		memcg = get_memcg(c);
1034 		old_memcg = set_active_memcg(memcg);
1035 		ret = __alloc(c, NUMA_NO_NODE, GFP_KERNEL | __GFP_NOWARN | __GFP_ACCOUNT);
1036 		if (ret)
1037 			*(struct bpf_mem_cache **)ret = c;
1038 		set_active_memcg(old_memcg);
1039 		mem_cgroup_put(memcg);
1040 	}
1041 
1042 	return !ret ? NULL : ret + LLIST_NODE_SZ;
1043 }
1044 
1045 int bpf_mem_alloc_check_size(bool percpu, size_t size)
1046 {
1047 	/* The size of percpu allocation doesn't have LLIST_NODE_SZ overhead */
1048 	if ((percpu && size > BPF_MEM_ALLOC_SIZE_MAX) ||
1049 	    (!percpu && size > BPF_MEM_ALLOC_SIZE_MAX - LLIST_NODE_SZ))
1050 		return -E2BIG;
1051 
1052 	return 0;
1053 }
1054 
1055 void bpf_mem_alloc_set_dtor(struct bpf_mem_alloc *ma, void (*dtor)(void *obj, void *ctx),
1056 			    void (*dtor_ctx_free)(void *ctx), void *ctx)
1057 {
1058 	struct bpf_mem_caches *cc;
1059 	struct bpf_mem_cache *c;
1060 	int cpu, i;
1061 
1062 	ma->dtor_ctx_free = dtor_ctx_free;
1063 	ma->dtor_ctx = ctx;
1064 
1065 	if (ma->cache) {
1066 		for_each_possible_cpu(cpu) {
1067 			c = per_cpu_ptr(ma->cache, cpu);
1068 			c->dtor = dtor;
1069 			c->dtor_ctx = ctx;
1070 		}
1071 	}
1072 	if (ma->caches) {
1073 		for_each_possible_cpu(cpu) {
1074 			cc = per_cpu_ptr(ma->caches, cpu);
1075 			for (i = 0; i < NUM_CACHES; i++) {
1076 				c = &cc->cache[i];
1077 				c->dtor = dtor;
1078 				c->dtor_ctx = ctx;
1079 			}
1080 		}
1081 	}
1082 }
1083