xref: /linux/kernel/bpf/memalloc.c (revision 9beda16c)
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 	struct bpf_mem_cache *tgt;
103 
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;
109 	struct rcu_head rcu;
110 	atomic_t call_rcu_in_progress;
111 	struct llist_head free_llist_extra_rcu;
112 
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;
118 };
119 
120 struct bpf_mem_caches {
121 	struct bpf_mem_cache cache[NUM_CACHES];
122 };
123 
124 static struct llist_node notrace *__llist_del_first(struct llist_head *head)
125 {
126 	struct llist_node *entry, *next;
127 
128 	entry = head->first;
129 	if (!entry)
130 		return NULL;
131 	next = entry->next;
132 	head->first = next;
133 	return entry;
134 }
135 
136 static void *__alloc(struct bpf_mem_cache *c, int node, gfp_t flags)
137 {
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);
141 
142 		if (!obj || !pptr) {
143 			free_percpu(pptr);
144 			kfree(obj);
145 			return NULL;
146 		}
147 		obj[1] = pptr;
148 		return obj;
149 	}
150 
151 	return kmalloc_node(c->unit_size, flags | __GFP_ZERO, node);
152 }
153 
154 static struct mem_cgroup *get_memcg(const struct bpf_mem_cache *c)
155 {
156 #ifdef CONFIG_MEMCG_KMEM
157 	if (c->objcg)
158 		return get_mem_cgroup_from_objcg(c->objcg);
159 #endif
160 
161 #ifdef CONFIG_MEMCG
162 	return root_mem_cgroup;
163 #else
164 	return NULL;
165 #endif
166 }
167 
168 static void inc_active(struct bpf_mem_cache *c, unsigned long *flags)
169 {
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.
175 		 */
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.
182 	 */
183 	WARN_ON_ONCE(local_inc_return(&c->active) != 1);
184 }
185 
186 static void dec_active(struct bpf_mem_cache *c, unsigned long *flags)
187 {
188 	local_dec(&c->active);
189 	if (IS_ENABLED(CONFIG_PREEMPT_RT))
190 		local_irq_restore(*flags);
191 }
192 
193 static void add_obj_to_free_list(struct bpf_mem_cache *c, void *obj)
194 {
195 	unsigned long flags;
196 
197 	inc_active(c, &flags);
198 	__llist_add(obj, &c->free_llist);
199 	c->free_cnt++;
200 	dec_active(c, &flags);
201 }
202 
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)
205 {
206 	struct mem_cgroup *memcg = NULL, *old_memcg;
207 	gfp_t gfp;
208 	void *obj;
209 	int i;
210 
211 	gfp = __GFP_NOWARN | __GFP_ACCOUNT;
212 	gfp |= atomic ? GFP_NOWAIT : GFP_KERNEL;
213 
214 	for (i = 0; i < cnt; i++) {
215 		/*
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.
219 		 */
220 		obj = llist_del_first(&c->free_by_rcu_ttrace);
221 		if (!obj)
222 			break;
223 		add_obj_to_free_list(c, obj);
224 	}
225 	if (i >= cnt)
226 		return;
227 
228 	for (; i < cnt; i++) {
229 		obj = llist_del_first(&c->waiting_for_gp_ttrace);
230 		if (!obj)
231 			break;
232 		add_obj_to_free_list(c, obj);
233 	}
234 	if (i >= cnt)
235 		return;
236 
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
243 		 * want here.
244 		 */
245 		obj = __alloc(c, node, gfp);
246 		if (!obj)
247 			break;
248 		add_obj_to_free_list(c, obj);
249 	}
250 	set_active_memcg(old_memcg);
251 	mem_cgroup_put(memcg);
252 }
253 
254 static void free_one(void *obj, bool percpu)
255 {
256 	if (percpu) {
257 		free_percpu(((void **)obj)[1]);
258 		kfree(obj);
259 		return;
260 	}
261 
262 	kfree(obj);
263 }
264 
265 static int free_all(struct llist_node *llnode, bool percpu)
266 {
267 	struct llist_node *pos, *t;
268 	int cnt = 0;
269 
270 	llist_for_each_safe(pos, t, llnode) {
271 		free_one(pos, percpu);
272 		cnt++;
273 	}
274 	return cnt;
275 }
276 
277 static void __free_rcu(struct rcu_head *head)
278 {
279 	struct bpf_mem_cache *c = container_of(head, struct bpf_mem_cache, rcu_ttrace);
280 
281 	free_all(llist_del_all(&c->waiting_for_gp_ttrace), !!c->percpu_size);
282 	atomic_set(&c->call_rcu_ttrace_in_progress, 0);
283 }
284 
285 static void __free_rcu_tasks_trace(struct rcu_head *head)
286 {
287 	/* If RCU Tasks Trace grace period implies RCU grace period,
288 	 * there is no need to invoke call_rcu().
289 	 */
290 	if (rcu_trace_implies_rcu_gp())
291 		__free_rcu(head);
292 	else
293 		call_rcu(head, __free_rcu);
294 }
295 
296 static void enque_to_free(struct bpf_mem_cache *c, void *obj)
297 {
298 	struct llist_node *llnode = obj;
299 
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.
302 	 */
303 	llist_add(llnode, &c->free_by_rcu_ttrace);
304 }
305 
306 static void do_call_rcu_ttrace(struct bpf_mem_cache *c)
307 {
308 	struct llist_node *llnode, *t;
309 
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);
314 		}
315 		return;
316 	}
317 
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);
321 
322 	if (unlikely(READ_ONCE(c->draining))) {
323 		__free_rcu(&c->rcu_ttrace);
324 		return;
325 	}
326 
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.
331 	 */
332 	call_rcu_tasks_trace(&c->rcu_ttrace, __free_rcu_tasks_trace);
333 }
334 
335 static void free_bulk(struct bpf_mem_cache *c)
336 {
337 	struct bpf_mem_cache *tgt = c->tgt;
338 	struct llist_node *llnode, *t;
339 	unsigned long flags;
340 	int cnt;
341 
342 	WARN_ON_ONCE(tgt->unit_size != c->unit_size);
343 	WARN_ON_ONCE(tgt->percpu_size != c->percpu_size);
344 
345 	do {
346 		inc_active(c, &flags);
347 		llnode = __llist_del_first(&c->free_llist);
348 		if (llnode)
349 			cnt = --c->free_cnt;
350 		else
351 			cnt = 0;
352 		dec_active(c, &flags);
353 		if (llnode)
354 			enque_to_free(tgt, llnode);
355 	} while (cnt > (c->high_watermark + c->low_watermark) / 2);
356 
357 	/* and drain free_llist_extra */
358 	llist_for_each_safe(llnode, t, llist_del_all(&c->free_llist_extra))
359 		enque_to_free(tgt, llnode);
360 	do_call_rcu_ttrace(tgt);
361 }
362 
363 static void __free_by_rcu(struct rcu_head *head)
364 {
365 	struct bpf_mem_cache *c = container_of(head, struct bpf_mem_cache, rcu);
366 	struct bpf_mem_cache *tgt = c->tgt;
367 	struct llist_node *llnode;
368 
369 	WARN_ON_ONCE(tgt->unit_size != c->unit_size);
370 	WARN_ON_ONCE(tgt->percpu_size != c->percpu_size);
371 
372 	llnode = llist_del_all(&c->waiting_for_gp);
373 	if (!llnode)
374 		goto out;
375 
376 	llist_add_batch(llnode, c->waiting_for_gp_tail, &tgt->free_by_rcu_ttrace);
377 
378 	/* Objects went through regular RCU GP. Send them to RCU tasks trace */
379 	do_call_rcu_ttrace(tgt);
380 out:
381 	atomic_set(&c->call_rcu_in_progress, 0);
382 }
383 
384 static void check_free_by_rcu(struct bpf_mem_cache *c)
385 {
386 	struct llist_node *llnode, *t;
387 	unsigned long flags;
388 
389 	/* drain free_llist_extra_rcu */
390 	if (unlikely(!llist_empty(&c->free_llist_extra_rcu))) {
391 		inc_active(c, &flags);
392 		llist_for_each_safe(llnode, t, llist_del_all(&c->free_llist_extra_rcu))
393 			if (__llist_add(llnode, &c->free_by_rcu))
394 				c->free_by_rcu_tail = llnode;
395 		dec_active(c, &flags);
396 	}
397 
398 	if (llist_empty(&c->free_by_rcu))
399 		return;
400 
401 	if (atomic_xchg(&c->call_rcu_in_progress, 1)) {
402 		/*
403 		 * Instead of kmalloc-ing new rcu_head and triggering 10k
404 		 * call_rcu() to hit rcutree.qhimark and force RCU to notice
405 		 * the overload just ask RCU to hurry up. There could be many
406 		 * objects in free_by_rcu list.
407 		 * This hint reduces memory consumption for an artificial
408 		 * benchmark from 2 Gbyte to 150 Mbyte.
409 		 */
410 		rcu_request_urgent_qs_task(current);
411 		return;
412 	}
413 
414 	WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp));
415 
416 	inc_active(c, &flags);
417 	WRITE_ONCE(c->waiting_for_gp.first, __llist_del_all(&c->free_by_rcu));
418 	c->waiting_for_gp_tail = c->free_by_rcu_tail;
419 	dec_active(c, &flags);
420 
421 	if (unlikely(READ_ONCE(c->draining))) {
422 		free_all(llist_del_all(&c->waiting_for_gp), !!c->percpu_size);
423 		atomic_set(&c->call_rcu_in_progress, 0);
424 	} else {
425 		call_rcu_hurry(&c->rcu, __free_by_rcu);
426 	}
427 }
428 
429 static void bpf_mem_refill(struct irq_work *work)
430 {
431 	struct bpf_mem_cache *c = container_of(work, struct bpf_mem_cache, refill_work);
432 	int cnt;
433 
434 	/* Racy access to free_cnt. It doesn't need to be 100% accurate */
435 	cnt = c->free_cnt;
436 	if (cnt < c->low_watermark)
437 		/* irq_work runs on this cpu and kmalloc will allocate
438 		 * from the current numa node which is what we want here.
439 		 */
440 		alloc_bulk(c, c->batch, NUMA_NO_NODE, true);
441 	else if (cnt > c->high_watermark)
442 		free_bulk(c);
443 
444 	check_free_by_rcu(c);
445 }
446 
447 static void notrace irq_work_raise(struct bpf_mem_cache *c)
448 {
449 	irq_work_queue(&c->refill_work);
450 }
451 
452 /* For typical bpf map case that uses bpf_mem_cache_alloc and single bucket
453  * the freelist cache will be elem_size * 64 (or less) on each cpu.
454  *
455  * For bpf programs that don't have statically known allocation sizes and
456  * assuming (low_mark + high_mark) / 2 as an average number of elements per
457  * bucket and all buckets are used the total amount of memory in freelists
458  * on each cpu will be:
459  * 64*16 + 64*32 + 64*64 + 64*96 + 64*128 + 64*196 + 64*256 + 32*512 + 16*1024 + 8*2048 + 4*4096
460  * == ~ 116 Kbyte using below heuristic.
461  * Initialized, but unused bpf allocator (not bpf map specific one) will
462  * consume ~ 11 Kbyte per cpu.
463  * Typical case will be between 11K and 116K closer to 11K.
464  * bpf progs can and should share bpf_mem_cache when possible.
465  */
466 static void init_refill_work(struct bpf_mem_cache *c)
467 {
468 	init_irq_work(&c->refill_work, bpf_mem_refill);
469 	if (c->unit_size <= 256) {
470 		c->low_watermark = 32;
471 		c->high_watermark = 96;
472 	} else {
473 		/* When page_size == 4k, order-0 cache will have low_mark == 2
474 		 * and high_mark == 6 with batch alloc of 3 individual pages at
475 		 * a time.
476 		 * 8k allocs and above low == 1, high == 3, batch == 1.
477 		 */
478 		c->low_watermark = max(32 * 256 / c->unit_size, 1);
479 		c->high_watermark = max(96 * 256 / c->unit_size, 3);
480 	}
481 	c->batch = max((c->high_watermark - c->low_watermark) / 4 * 3, 1);
482 }
483 
484 static void prefill_mem_cache(struct bpf_mem_cache *c, int cpu)
485 {
486 	/* To avoid consuming memory assume that 1st run of bpf
487 	 * prog won't be doing more than 4 map_update_elem from
488 	 * irq disabled region
489 	 */
490 	alloc_bulk(c, c->unit_size <= 256 ? 4 : 1, cpu_to_node(cpu), false);
491 }
492 
493 /* When size != 0 bpf_mem_cache for each cpu.
494  * This is typical bpf hash map use case when all elements have equal size.
495  *
496  * When size == 0 allocate 11 bpf_mem_cache-s for each cpu, then rely on
497  * kmalloc/kfree. Max allocation size is 4096 in this case.
498  * This is bpf_dynptr and bpf_kptr use case.
499  */
500 int bpf_mem_alloc_init(struct bpf_mem_alloc *ma, int size, bool percpu)
501 {
502 	static u16 sizes[NUM_CACHES] = {96, 192, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096};
503 	struct bpf_mem_caches *cc, __percpu *pcc;
504 	struct bpf_mem_cache *c, __percpu *pc;
505 	struct obj_cgroup *objcg = NULL;
506 	int cpu, i, unit_size, percpu_size = 0;
507 
508 	/* room for llist_node and per-cpu pointer */
509 	if (percpu)
510 		percpu_size = LLIST_NODE_SZ + sizeof(void *);
511 	ma->percpu = percpu;
512 
513 	if (size) {
514 		pc = __alloc_percpu_gfp(sizeof(*pc), 8, GFP_KERNEL);
515 		if (!pc)
516 			return -ENOMEM;
517 
518 		if (!percpu)
519 			size += LLIST_NODE_SZ; /* room for llist_node */
520 		unit_size = size;
521 
522 #ifdef CONFIG_MEMCG_KMEM
523 		if (memcg_bpf_enabled())
524 			objcg = get_obj_cgroup_from_current();
525 #endif
526 		for_each_possible_cpu(cpu) {
527 			c = per_cpu_ptr(pc, cpu);
528 			c->unit_size = unit_size;
529 			c->objcg = objcg;
530 			c->percpu_size = percpu_size;
531 			c->tgt = c;
532 			init_refill_work(c);
533 			prefill_mem_cache(c, cpu);
534 		}
535 		ma->cache = pc;
536 		return 0;
537 	}
538 
539 	pcc = __alloc_percpu_gfp(sizeof(*cc), 8, GFP_KERNEL);
540 	if (!pcc)
541 		return -ENOMEM;
542 #ifdef CONFIG_MEMCG_KMEM
543 	objcg = get_obj_cgroup_from_current();
544 #endif
545 	for_each_possible_cpu(cpu) {
546 		cc = per_cpu_ptr(pcc, cpu);
547 		for (i = 0; i < NUM_CACHES; i++) {
548 			c = &cc->cache[i];
549 			c->unit_size = sizes[i];
550 			c->objcg = objcg;
551 			c->percpu_size = percpu_size;
552 			c->tgt = c;
553 
554 			init_refill_work(c);
555 			prefill_mem_cache(c, cpu);
556 		}
557 	}
558 
559 	ma->caches = pcc;
560 	return 0;
561 }
562 
563 static void drain_mem_cache(struct bpf_mem_cache *c)
564 {
565 	bool percpu = !!c->percpu_size;
566 
567 	/* No progs are using this bpf_mem_cache, but htab_map_free() called
568 	 * bpf_mem_cache_free() for all remaining elements and they can be in
569 	 * free_by_rcu_ttrace or in waiting_for_gp_ttrace lists, so drain those lists now.
570 	 *
571 	 * Except for waiting_for_gp_ttrace list, there are no concurrent operations
572 	 * on these lists, so it is safe to use __llist_del_all().
573 	 */
574 	free_all(llist_del_all(&c->free_by_rcu_ttrace), percpu);
575 	free_all(llist_del_all(&c->waiting_for_gp_ttrace), percpu);
576 	free_all(__llist_del_all(&c->free_llist), percpu);
577 	free_all(__llist_del_all(&c->free_llist_extra), percpu);
578 	free_all(__llist_del_all(&c->free_by_rcu), percpu);
579 	free_all(__llist_del_all(&c->free_llist_extra_rcu), percpu);
580 	free_all(llist_del_all(&c->waiting_for_gp), percpu);
581 }
582 
583 static void check_mem_cache(struct bpf_mem_cache *c)
584 {
585 	WARN_ON_ONCE(!llist_empty(&c->free_by_rcu_ttrace));
586 	WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp_ttrace));
587 	WARN_ON_ONCE(!llist_empty(&c->free_llist));
588 	WARN_ON_ONCE(!llist_empty(&c->free_llist_extra));
589 	WARN_ON_ONCE(!llist_empty(&c->free_by_rcu));
590 	WARN_ON_ONCE(!llist_empty(&c->free_llist_extra_rcu));
591 	WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp));
592 }
593 
594 static void check_leaked_objs(struct bpf_mem_alloc *ma)
595 {
596 	struct bpf_mem_caches *cc;
597 	struct bpf_mem_cache *c;
598 	int cpu, i;
599 
600 	if (ma->cache) {
601 		for_each_possible_cpu(cpu) {
602 			c = per_cpu_ptr(ma->cache, cpu);
603 			check_mem_cache(c);
604 		}
605 	}
606 	if (ma->caches) {
607 		for_each_possible_cpu(cpu) {
608 			cc = per_cpu_ptr(ma->caches, cpu);
609 			for (i = 0; i < NUM_CACHES; i++) {
610 				c = &cc->cache[i];
611 				check_mem_cache(c);
612 			}
613 		}
614 	}
615 }
616 
617 static void free_mem_alloc_no_barrier(struct bpf_mem_alloc *ma)
618 {
619 	check_leaked_objs(ma);
620 	free_percpu(ma->cache);
621 	free_percpu(ma->caches);
622 	ma->cache = NULL;
623 	ma->caches = NULL;
624 }
625 
626 static void free_mem_alloc(struct bpf_mem_alloc *ma)
627 {
628 	/* waiting_for_gp[_ttrace] lists were drained, but RCU callbacks
629 	 * might still execute. Wait for them.
630 	 *
631 	 * rcu_barrier_tasks_trace() doesn't imply synchronize_rcu_tasks_trace(),
632 	 * but rcu_barrier_tasks_trace() and rcu_barrier() below are only used
633 	 * to wait for the pending __free_rcu_tasks_trace() and __free_rcu(),
634 	 * so if call_rcu(head, __free_rcu) is skipped due to
635 	 * rcu_trace_implies_rcu_gp(), it will be OK to skip rcu_barrier() by
636 	 * using rcu_trace_implies_rcu_gp() as well.
637 	 */
638 	rcu_barrier(); /* wait for __free_by_rcu */
639 	rcu_barrier_tasks_trace(); /* wait for __free_rcu */
640 	if (!rcu_trace_implies_rcu_gp())
641 		rcu_barrier();
642 	free_mem_alloc_no_barrier(ma);
643 }
644 
645 static void free_mem_alloc_deferred(struct work_struct *work)
646 {
647 	struct bpf_mem_alloc *ma = container_of(work, struct bpf_mem_alloc, work);
648 
649 	free_mem_alloc(ma);
650 	kfree(ma);
651 }
652 
653 static void destroy_mem_alloc(struct bpf_mem_alloc *ma, int rcu_in_progress)
654 {
655 	struct bpf_mem_alloc *copy;
656 
657 	if (!rcu_in_progress) {
658 		/* Fast path. No callbacks are pending, hence no need to do
659 		 * rcu_barrier-s.
660 		 */
661 		free_mem_alloc_no_barrier(ma);
662 		return;
663 	}
664 
665 	copy = kmemdup(ma, sizeof(*ma), GFP_KERNEL);
666 	if (!copy) {
667 		/* Slow path with inline barrier-s */
668 		free_mem_alloc(ma);
669 		return;
670 	}
671 
672 	/* Defer barriers into worker to let the rest of map memory to be freed */
673 	memset(ma, 0, sizeof(*ma));
674 	INIT_WORK(&copy->work, free_mem_alloc_deferred);
675 	queue_work(system_unbound_wq, &copy->work);
676 }
677 
678 void bpf_mem_alloc_destroy(struct bpf_mem_alloc *ma)
679 {
680 	struct bpf_mem_caches *cc;
681 	struct bpf_mem_cache *c;
682 	int cpu, i, rcu_in_progress;
683 
684 	if (ma->cache) {
685 		rcu_in_progress = 0;
686 		for_each_possible_cpu(cpu) {
687 			c = per_cpu_ptr(ma->cache, cpu);
688 			WRITE_ONCE(c->draining, true);
689 			irq_work_sync(&c->refill_work);
690 			drain_mem_cache(c);
691 			rcu_in_progress += atomic_read(&c->call_rcu_ttrace_in_progress);
692 			rcu_in_progress += atomic_read(&c->call_rcu_in_progress);
693 		}
694 		/* objcg is the same across cpus */
695 		if (c->objcg)
696 			obj_cgroup_put(c->objcg);
697 		destroy_mem_alloc(ma, rcu_in_progress);
698 	}
699 	if (ma->caches) {
700 		rcu_in_progress = 0;
701 		for_each_possible_cpu(cpu) {
702 			cc = per_cpu_ptr(ma->caches, cpu);
703 			for (i = 0; i < NUM_CACHES; i++) {
704 				c = &cc->cache[i];
705 				WRITE_ONCE(c->draining, true);
706 				irq_work_sync(&c->refill_work);
707 				drain_mem_cache(c);
708 				rcu_in_progress += atomic_read(&c->call_rcu_ttrace_in_progress);
709 				rcu_in_progress += atomic_read(&c->call_rcu_in_progress);
710 			}
711 		}
712 		if (c->objcg)
713 			obj_cgroup_put(c->objcg);
714 		destroy_mem_alloc(ma, rcu_in_progress);
715 	}
716 }
717 
718 /* notrace is necessary here and in other functions to make sure
719  * bpf programs cannot attach to them and cause llist corruptions.
720  */
721 static void notrace *unit_alloc(struct bpf_mem_cache *c)
722 {
723 	struct llist_node *llnode = NULL;
724 	unsigned long flags;
725 	int cnt = 0;
726 
727 	/* Disable irqs to prevent the following race for majority of prog types:
728 	 * prog_A
729 	 *   bpf_mem_alloc
730 	 *      preemption or irq -> prog_B
731 	 *        bpf_mem_alloc
732 	 *
733 	 * but prog_B could be a perf_event NMI prog.
734 	 * Use per-cpu 'active' counter to order free_list access between
735 	 * unit_alloc/unit_free/bpf_mem_refill.
736 	 */
737 	local_irq_save(flags);
738 	if (local_inc_return(&c->active) == 1) {
739 		llnode = __llist_del_first(&c->free_llist);
740 		if (llnode) {
741 			cnt = --c->free_cnt;
742 			*(struct bpf_mem_cache **)llnode = c;
743 		}
744 	}
745 	local_dec(&c->active);
746 
747 	WARN_ON(cnt < 0);
748 
749 	if (cnt < c->low_watermark)
750 		irq_work_raise(c);
751 	/* Enable IRQ after the enqueue of irq work completes, so irq work
752 	 * will run after IRQ is enabled and free_llist may be refilled by
753 	 * irq work before other task preempts current task.
754 	 */
755 	local_irq_restore(flags);
756 
757 	return llnode;
758 }
759 
760 /* Though 'ptr' object could have been allocated on a different cpu
761  * add it to the free_llist of the current cpu.
762  * Let kfree() logic deal with it when it's later called from irq_work.
763  */
764 static void notrace unit_free(struct bpf_mem_cache *c, void *ptr)
765 {
766 	struct llist_node *llnode = ptr - LLIST_NODE_SZ;
767 	unsigned long flags;
768 	int cnt = 0;
769 
770 	BUILD_BUG_ON(LLIST_NODE_SZ > 8);
771 
772 	/*
773 	 * Remember bpf_mem_cache that allocated this object.
774 	 * The hint is not accurate.
775 	 */
776 	c->tgt = *(struct bpf_mem_cache **)llnode;
777 
778 	local_irq_save(flags);
779 	if (local_inc_return(&c->active) == 1) {
780 		__llist_add(llnode, &c->free_llist);
781 		cnt = ++c->free_cnt;
782 	} else {
783 		/* unit_free() cannot fail. Therefore add an object to atomic
784 		 * llist. free_bulk() will drain it. Though free_llist_extra is
785 		 * a per-cpu list we have to use atomic llist_add here, since
786 		 * it also can be interrupted by bpf nmi prog that does another
787 		 * unit_free() into the same free_llist_extra.
788 		 */
789 		llist_add(llnode, &c->free_llist_extra);
790 	}
791 	local_dec(&c->active);
792 
793 	if (cnt > c->high_watermark)
794 		/* free few objects from current cpu into global kmalloc pool */
795 		irq_work_raise(c);
796 	/* Enable IRQ after irq_work_raise() completes, otherwise when current
797 	 * task is preempted by task which does unit_alloc(), unit_alloc() may
798 	 * return NULL unexpectedly because irq work is already pending but can
799 	 * not been triggered and free_llist can not be refilled timely.
800 	 */
801 	local_irq_restore(flags);
802 }
803 
804 static void notrace unit_free_rcu(struct bpf_mem_cache *c, void *ptr)
805 {
806 	struct llist_node *llnode = ptr - LLIST_NODE_SZ;
807 	unsigned long flags;
808 
809 	c->tgt = *(struct bpf_mem_cache **)llnode;
810 
811 	local_irq_save(flags);
812 	if (local_inc_return(&c->active) == 1) {
813 		if (__llist_add(llnode, &c->free_by_rcu))
814 			c->free_by_rcu_tail = llnode;
815 	} else {
816 		llist_add(llnode, &c->free_llist_extra_rcu);
817 	}
818 	local_dec(&c->active);
819 
820 	if (!atomic_read(&c->call_rcu_in_progress))
821 		irq_work_raise(c);
822 	local_irq_restore(flags);
823 }
824 
825 /* Called from BPF program or from sys_bpf syscall.
826  * In both cases migration is disabled.
827  */
828 void notrace *bpf_mem_alloc(struct bpf_mem_alloc *ma, size_t size)
829 {
830 	int idx;
831 	void *ret;
832 
833 	if (!size)
834 		return NULL;
835 
836 	if (!ma->percpu)
837 		size += LLIST_NODE_SZ;
838 	idx = bpf_mem_cache_idx(size);
839 	if (idx < 0)
840 		return NULL;
841 
842 	ret = unit_alloc(this_cpu_ptr(ma->caches)->cache + idx);
843 	return !ret ? NULL : ret + LLIST_NODE_SZ;
844 }
845 
846 void notrace bpf_mem_free(struct bpf_mem_alloc *ma, void *ptr)
847 {
848 	struct bpf_mem_cache *c;
849 	int idx;
850 
851 	if (!ptr)
852 		return;
853 
854 	c = *(void **)(ptr - LLIST_NODE_SZ);
855 	idx = bpf_mem_cache_idx(c->unit_size);
856 	if (WARN_ON_ONCE(idx < 0))
857 		return;
858 
859 	unit_free(this_cpu_ptr(ma->caches)->cache + idx, ptr);
860 }
861 
862 void notrace bpf_mem_free_rcu(struct bpf_mem_alloc *ma, void *ptr)
863 {
864 	struct bpf_mem_cache *c;
865 	int idx;
866 
867 	if (!ptr)
868 		return;
869 
870 	c = *(void **)(ptr - LLIST_NODE_SZ);
871 	idx = bpf_mem_cache_idx(c->unit_size);
872 	if (WARN_ON_ONCE(idx < 0))
873 		return;
874 
875 	unit_free_rcu(this_cpu_ptr(ma->caches)->cache + idx, ptr);
876 }
877 
878 void notrace *bpf_mem_cache_alloc(struct bpf_mem_alloc *ma)
879 {
880 	void *ret;
881 
882 	ret = unit_alloc(this_cpu_ptr(ma->cache));
883 	return !ret ? NULL : ret + LLIST_NODE_SZ;
884 }
885 
886 void notrace bpf_mem_cache_free(struct bpf_mem_alloc *ma, void *ptr)
887 {
888 	if (!ptr)
889 		return;
890 
891 	unit_free(this_cpu_ptr(ma->cache), ptr);
892 }
893 
894 void notrace bpf_mem_cache_free_rcu(struct bpf_mem_alloc *ma, void *ptr)
895 {
896 	if (!ptr)
897 		return;
898 
899 	unit_free_rcu(this_cpu_ptr(ma->cache), ptr);
900 }
901 
902 /* Directly does a kfree() without putting 'ptr' back to the free_llist
903  * for reuse and without waiting for a rcu_tasks_trace gp.
904  * The caller must first go through the rcu_tasks_trace gp for 'ptr'
905  * before calling bpf_mem_cache_raw_free().
906  * It could be used when the rcu_tasks_trace callback does not have
907  * a hold on the original bpf_mem_alloc object that allocated the
908  * 'ptr'. This should only be used in the uncommon code path.
909  * Otherwise, the bpf_mem_alloc's free_llist cannot be refilled
910  * and may affect performance.
911  */
912 void bpf_mem_cache_raw_free(void *ptr)
913 {
914 	if (!ptr)
915 		return;
916 
917 	kfree(ptr - LLIST_NODE_SZ);
918 }
919 
920 /* When flags == GFP_KERNEL, it signals that the caller will not cause
921  * deadlock when using kmalloc. bpf_mem_cache_alloc_flags() will use
922  * kmalloc if the free_llist is empty.
923  */
924 void notrace *bpf_mem_cache_alloc_flags(struct bpf_mem_alloc *ma, gfp_t flags)
925 {
926 	struct bpf_mem_cache *c;
927 	void *ret;
928 
929 	c = this_cpu_ptr(ma->cache);
930 
931 	ret = unit_alloc(c);
932 	if (!ret && flags == GFP_KERNEL) {
933 		struct mem_cgroup *memcg, *old_memcg;
934 
935 		memcg = get_memcg(c);
936 		old_memcg = set_active_memcg(memcg);
937 		ret = __alloc(c, NUMA_NO_NODE, GFP_KERNEL | __GFP_NOWARN | __GFP_ACCOUNT);
938 		if (ret)
939 			*(struct bpf_mem_cache **)ret = c;
940 		set_active_memcg(old_memcg);
941 		mem_cgroup_put(memcg);
942 	}
943 
944 	return !ret ? NULL : ret + LLIST_NODE_SZ;
945 }
946