xref: /linux/kernel/bpf/trampoline.c (revision 27b3f70553432114b3d26f4d9c72cf02f38b84ee)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2019 Facebook */
3 #include <linux/hash.h>
4 #include <linux/bpf.h>
5 #include <linux/filter.h>
6 #include <linux/ftrace.h>
7 #include <linux/rbtree_latch.h>
8 #include <linux/perf_event.h>
9 #include <linux/btf.h>
10 #include <linux/rcupdate_trace.h>
11 #include <linux/rcupdate_wait.h>
12 #include <linux/module.h>
13 #include <linux/static_call.h>
14 #include <linux/bpf_verifier.h>
15 #include <linux/bpf_lsm.h>
16 
17 /* dummy _ops. The verifier will operate on target program's ops. */
18 const struct bpf_verifier_ops bpf_extension_verifier_ops = {
19 };
20 const struct bpf_prog_ops bpf_extension_prog_ops = {
21 };
22 
23 /* btf_vmlinux has ~22k attachable functions. 1k htab is enough. */
24 #define TRAMPOLINE_HASH_BITS 10
25 #define TRAMPOLINE_TABLE_SIZE (1 << TRAMPOLINE_HASH_BITS)
26 
27 static struct hlist_head trampoline_table[TRAMPOLINE_TABLE_SIZE];
28 
29 /* serializes access to trampoline_table */
30 static DEFINE_MUTEX(trampoline_mutex);
31 
32 bool bpf_prog_has_trampoline(const struct bpf_prog *prog)
33 {
34 	enum bpf_attach_type eatype = prog->expected_attach_type;
35 	enum bpf_prog_type ptype = prog->type;
36 
37 	return (ptype == BPF_PROG_TYPE_TRACING &&
38 		(eatype == BPF_TRACE_FENTRY || eatype == BPF_TRACE_FEXIT ||
39 		 eatype == BPF_MODIFY_RETURN)) ||
40 		(ptype == BPF_PROG_TYPE_LSM && eatype == BPF_LSM_MAC);
41 }
42 
43 void *bpf_jit_alloc_exec_page(void)
44 {
45 	void *image;
46 
47 	image = bpf_jit_alloc_exec(PAGE_SIZE);
48 	if (!image)
49 		return NULL;
50 
51 	set_vm_flush_reset_perms(image);
52 	/* Keep image as writeable. The alternative is to keep flipping ro/rw
53 	 * every time new program is attached or detached.
54 	 */
55 	set_memory_x((long)image, 1);
56 	return image;
57 }
58 
59 void bpf_image_ksym_add(void *data, struct bpf_ksym *ksym)
60 {
61 	ksym->start = (unsigned long) data;
62 	ksym->end = ksym->start + PAGE_SIZE;
63 	bpf_ksym_add(ksym);
64 	perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, ksym->start,
65 			   PAGE_SIZE, false, ksym->name);
66 }
67 
68 void bpf_image_ksym_del(struct bpf_ksym *ksym)
69 {
70 	bpf_ksym_del(ksym);
71 	perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, ksym->start,
72 			   PAGE_SIZE, true, ksym->name);
73 }
74 
75 static struct bpf_trampoline *bpf_trampoline_lookup(u64 key)
76 {
77 	struct bpf_trampoline *tr;
78 	struct hlist_head *head;
79 	int i;
80 
81 	mutex_lock(&trampoline_mutex);
82 	head = &trampoline_table[hash_64(key, TRAMPOLINE_HASH_BITS)];
83 	hlist_for_each_entry(tr, head, hlist) {
84 		if (tr->key == key) {
85 			refcount_inc(&tr->refcnt);
86 			goto out;
87 		}
88 	}
89 	tr = kzalloc(sizeof(*tr), GFP_KERNEL);
90 	if (!tr)
91 		goto out;
92 
93 	tr->key = key;
94 	INIT_HLIST_NODE(&tr->hlist);
95 	hlist_add_head(&tr->hlist, head);
96 	refcount_set(&tr->refcnt, 1);
97 	mutex_init(&tr->mutex);
98 	for (i = 0; i < BPF_TRAMP_MAX; i++)
99 		INIT_HLIST_HEAD(&tr->progs_hlist[i]);
100 out:
101 	mutex_unlock(&trampoline_mutex);
102 	return tr;
103 }
104 
105 static int bpf_trampoline_module_get(struct bpf_trampoline *tr)
106 {
107 	struct module *mod;
108 	int err = 0;
109 
110 	preempt_disable();
111 	mod = __module_text_address((unsigned long) tr->func.addr);
112 	if (mod && !try_module_get(mod))
113 		err = -ENOENT;
114 	preempt_enable();
115 	tr->mod = mod;
116 	return err;
117 }
118 
119 static void bpf_trampoline_module_put(struct bpf_trampoline *tr)
120 {
121 	module_put(tr->mod);
122 	tr->mod = NULL;
123 }
124 
125 static int unregister_fentry(struct bpf_trampoline *tr, void *old_addr)
126 {
127 	void *ip = tr->func.addr;
128 	int ret;
129 
130 	if (tr->func.ftrace_managed)
131 		ret = unregister_ftrace_direct((long)ip, (long)old_addr);
132 	else
133 		ret = bpf_arch_text_poke(ip, BPF_MOD_CALL, old_addr, NULL);
134 
135 	if (!ret)
136 		bpf_trampoline_module_put(tr);
137 	return ret;
138 }
139 
140 static int modify_fentry(struct bpf_trampoline *tr, void *old_addr, void *new_addr)
141 {
142 	void *ip = tr->func.addr;
143 	int ret;
144 
145 	if (tr->func.ftrace_managed)
146 		ret = modify_ftrace_direct((long)ip, (long)old_addr, (long)new_addr);
147 	else
148 		ret = bpf_arch_text_poke(ip, BPF_MOD_CALL, old_addr, new_addr);
149 	return ret;
150 }
151 
152 /* first time registering */
153 static int register_fentry(struct bpf_trampoline *tr, void *new_addr)
154 {
155 	void *ip = tr->func.addr;
156 	unsigned long faddr;
157 	int ret;
158 
159 	faddr = ftrace_location((unsigned long)ip);
160 	if (faddr)
161 		tr->func.ftrace_managed = true;
162 
163 	if (bpf_trampoline_module_get(tr))
164 		return -ENOENT;
165 
166 	if (tr->func.ftrace_managed)
167 		ret = register_ftrace_direct((long)ip, (long)new_addr);
168 	else
169 		ret = bpf_arch_text_poke(ip, BPF_MOD_CALL, NULL, new_addr);
170 
171 	if (ret)
172 		bpf_trampoline_module_put(tr);
173 	return ret;
174 }
175 
176 static struct bpf_tramp_links *
177 bpf_trampoline_get_progs(const struct bpf_trampoline *tr, int *total, bool *ip_arg)
178 {
179 	struct bpf_tramp_link *link;
180 	struct bpf_tramp_links *tlinks;
181 	struct bpf_tramp_link **links;
182 	int kind;
183 
184 	*total = 0;
185 	tlinks = kcalloc(BPF_TRAMP_MAX, sizeof(*tlinks), GFP_KERNEL);
186 	if (!tlinks)
187 		return ERR_PTR(-ENOMEM);
188 
189 	for (kind = 0; kind < BPF_TRAMP_MAX; kind++) {
190 		tlinks[kind].nr_links = tr->progs_cnt[kind];
191 		*total += tr->progs_cnt[kind];
192 		links = tlinks[kind].links;
193 
194 		hlist_for_each_entry(link, &tr->progs_hlist[kind], tramp_hlist) {
195 			*ip_arg |= link->link.prog->call_get_func_ip;
196 			*links++ = link;
197 		}
198 	}
199 	return tlinks;
200 }
201 
202 static void __bpf_tramp_image_put_deferred(struct work_struct *work)
203 {
204 	struct bpf_tramp_image *im;
205 
206 	im = container_of(work, struct bpf_tramp_image, work);
207 	bpf_image_ksym_del(&im->ksym);
208 	bpf_jit_free_exec(im->image);
209 	bpf_jit_uncharge_modmem(PAGE_SIZE);
210 	percpu_ref_exit(&im->pcref);
211 	kfree_rcu(im, rcu);
212 }
213 
214 /* callback, fexit step 3 or fentry step 2 */
215 static void __bpf_tramp_image_put_rcu(struct rcu_head *rcu)
216 {
217 	struct bpf_tramp_image *im;
218 
219 	im = container_of(rcu, struct bpf_tramp_image, rcu);
220 	INIT_WORK(&im->work, __bpf_tramp_image_put_deferred);
221 	schedule_work(&im->work);
222 }
223 
224 /* callback, fexit step 2. Called after percpu_ref_kill confirms. */
225 static void __bpf_tramp_image_release(struct percpu_ref *pcref)
226 {
227 	struct bpf_tramp_image *im;
228 
229 	im = container_of(pcref, struct bpf_tramp_image, pcref);
230 	call_rcu_tasks(&im->rcu, __bpf_tramp_image_put_rcu);
231 }
232 
233 /* callback, fexit or fentry step 1 */
234 static void __bpf_tramp_image_put_rcu_tasks(struct rcu_head *rcu)
235 {
236 	struct bpf_tramp_image *im;
237 
238 	im = container_of(rcu, struct bpf_tramp_image, rcu);
239 	if (im->ip_after_call)
240 		/* the case of fmod_ret/fexit trampoline and CONFIG_PREEMPTION=y */
241 		percpu_ref_kill(&im->pcref);
242 	else
243 		/* the case of fentry trampoline */
244 		call_rcu_tasks(&im->rcu, __bpf_tramp_image_put_rcu);
245 }
246 
247 static void bpf_tramp_image_put(struct bpf_tramp_image *im)
248 {
249 	/* The trampoline image that calls original function is using:
250 	 * rcu_read_lock_trace to protect sleepable bpf progs
251 	 * rcu_read_lock to protect normal bpf progs
252 	 * percpu_ref to protect trampoline itself
253 	 * rcu tasks to protect trampoline asm not covered by percpu_ref
254 	 * (which are few asm insns before __bpf_tramp_enter and
255 	 *  after __bpf_tramp_exit)
256 	 *
257 	 * The trampoline is unreachable before bpf_tramp_image_put().
258 	 *
259 	 * First, patch the trampoline to avoid calling into fexit progs.
260 	 * The progs will be freed even if the original function is still
261 	 * executing or sleeping.
262 	 * In case of CONFIG_PREEMPT=y use call_rcu_tasks() to wait on
263 	 * first few asm instructions to execute and call into
264 	 * __bpf_tramp_enter->percpu_ref_get.
265 	 * Then use percpu_ref_kill to wait for the trampoline and the original
266 	 * function to finish.
267 	 * Then use call_rcu_tasks() to make sure few asm insns in
268 	 * the trampoline epilogue are done as well.
269 	 *
270 	 * In !PREEMPT case the task that got interrupted in the first asm
271 	 * insns won't go through an RCU quiescent state which the
272 	 * percpu_ref_kill will be waiting for. Hence the first
273 	 * call_rcu_tasks() is not necessary.
274 	 */
275 	if (im->ip_after_call) {
276 		int err = bpf_arch_text_poke(im->ip_after_call, BPF_MOD_JUMP,
277 					     NULL, im->ip_epilogue);
278 		WARN_ON(err);
279 		if (IS_ENABLED(CONFIG_PREEMPTION))
280 			call_rcu_tasks(&im->rcu, __bpf_tramp_image_put_rcu_tasks);
281 		else
282 			percpu_ref_kill(&im->pcref);
283 		return;
284 	}
285 
286 	/* The trampoline without fexit and fmod_ret progs doesn't call original
287 	 * function and doesn't use percpu_ref.
288 	 * Use call_rcu_tasks_trace() to wait for sleepable progs to finish.
289 	 * Then use call_rcu_tasks() to wait for the rest of trampoline asm
290 	 * and normal progs.
291 	 */
292 	call_rcu_tasks_trace(&im->rcu, __bpf_tramp_image_put_rcu_tasks);
293 }
294 
295 static struct bpf_tramp_image *bpf_tramp_image_alloc(u64 key, u32 idx)
296 {
297 	struct bpf_tramp_image *im;
298 	struct bpf_ksym *ksym;
299 	void *image;
300 	int err = -ENOMEM;
301 
302 	im = kzalloc(sizeof(*im), GFP_KERNEL);
303 	if (!im)
304 		goto out;
305 
306 	err = bpf_jit_charge_modmem(PAGE_SIZE);
307 	if (err)
308 		goto out_free_im;
309 
310 	err = -ENOMEM;
311 	im->image = image = bpf_jit_alloc_exec_page();
312 	if (!image)
313 		goto out_uncharge;
314 
315 	err = percpu_ref_init(&im->pcref, __bpf_tramp_image_release, 0, GFP_KERNEL);
316 	if (err)
317 		goto out_free_image;
318 
319 	ksym = &im->ksym;
320 	INIT_LIST_HEAD_RCU(&ksym->lnode);
321 	snprintf(ksym->name, KSYM_NAME_LEN, "bpf_trampoline_%llu_%u", key, idx);
322 	bpf_image_ksym_add(image, ksym);
323 	return im;
324 
325 out_free_image:
326 	bpf_jit_free_exec(im->image);
327 out_uncharge:
328 	bpf_jit_uncharge_modmem(PAGE_SIZE);
329 out_free_im:
330 	kfree(im);
331 out:
332 	return ERR_PTR(err);
333 }
334 
335 static int bpf_trampoline_update(struct bpf_trampoline *tr)
336 {
337 	struct bpf_tramp_image *im;
338 	struct bpf_tramp_links *tlinks;
339 	u32 flags = BPF_TRAMP_F_RESTORE_REGS;
340 	bool ip_arg = false;
341 	int err, total;
342 
343 	tlinks = bpf_trampoline_get_progs(tr, &total, &ip_arg);
344 	if (IS_ERR(tlinks))
345 		return PTR_ERR(tlinks);
346 
347 	if (total == 0) {
348 		err = unregister_fentry(tr, tr->cur_image->image);
349 		bpf_tramp_image_put(tr->cur_image);
350 		tr->cur_image = NULL;
351 		tr->selector = 0;
352 		goto out;
353 	}
354 
355 	im = bpf_tramp_image_alloc(tr->key, tr->selector);
356 	if (IS_ERR(im)) {
357 		err = PTR_ERR(im);
358 		goto out;
359 	}
360 
361 	if (tlinks[BPF_TRAMP_FEXIT].nr_links ||
362 	    tlinks[BPF_TRAMP_MODIFY_RETURN].nr_links)
363 		flags = BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_SKIP_FRAME;
364 
365 	if (ip_arg)
366 		flags |= BPF_TRAMP_F_IP_ARG;
367 
368 	err = arch_prepare_bpf_trampoline(im, im->image, im->image + PAGE_SIZE,
369 					  &tr->func.model, flags, tlinks,
370 					  tr->func.addr);
371 	if (err < 0)
372 		goto out;
373 
374 	WARN_ON(tr->cur_image && tr->selector == 0);
375 	WARN_ON(!tr->cur_image && tr->selector);
376 	if (tr->cur_image)
377 		/* progs already running at this address */
378 		err = modify_fentry(tr, tr->cur_image->image, im->image);
379 	else
380 		/* first time registering */
381 		err = register_fentry(tr, im->image);
382 	if (err)
383 		goto out;
384 	if (tr->cur_image)
385 		bpf_tramp_image_put(tr->cur_image);
386 	tr->cur_image = im;
387 	tr->selector++;
388 out:
389 	kfree(tlinks);
390 	return err;
391 }
392 
393 static enum bpf_tramp_prog_type bpf_attach_type_to_tramp(struct bpf_prog *prog)
394 {
395 	switch (prog->expected_attach_type) {
396 	case BPF_TRACE_FENTRY:
397 		return BPF_TRAMP_FENTRY;
398 	case BPF_MODIFY_RETURN:
399 		return BPF_TRAMP_MODIFY_RETURN;
400 	case BPF_TRACE_FEXIT:
401 		return BPF_TRAMP_FEXIT;
402 	case BPF_LSM_MAC:
403 		if (!prog->aux->attach_func_proto->type)
404 			/* The function returns void, we cannot modify its
405 			 * return value.
406 			 */
407 			return BPF_TRAMP_FEXIT;
408 		else
409 			return BPF_TRAMP_MODIFY_RETURN;
410 	default:
411 		return BPF_TRAMP_REPLACE;
412 	}
413 }
414 
415 static int __bpf_trampoline_link_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr)
416 {
417 	enum bpf_tramp_prog_type kind;
418 	struct bpf_tramp_link *link_exiting;
419 	int err = 0;
420 	int cnt = 0, i;
421 
422 	kind = bpf_attach_type_to_tramp(link->link.prog);
423 	if (tr->extension_prog)
424 		/* cannot attach fentry/fexit if extension prog is attached.
425 		 * cannot overwrite extension prog either.
426 		 */
427 		return -EBUSY;
428 
429 	for (i = 0; i < BPF_TRAMP_MAX; i++)
430 		cnt += tr->progs_cnt[i];
431 
432 	if (kind == BPF_TRAMP_REPLACE) {
433 		/* Cannot attach extension if fentry/fexit are in use. */
434 		if (cnt)
435 			return -EBUSY;
436 		tr->extension_prog = link->link.prog;
437 		return bpf_arch_text_poke(tr->func.addr, BPF_MOD_JUMP, NULL,
438 					  link->link.prog->bpf_func);
439 	}
440 	if (cnt >= BPF_MAX_TRAMP_LINKS)
441 		return -E2BIG;
442 	if (!hlist_unhashed(&link->tramp_hlist))
443 		/* prog already linked */
444 		return -EBUSY;
445 	hlist_for_each_entry(link_exiting, &tr->progs_hlist[kind], tramp_hlist) {
446 		if (link_exiting->link.prog != link->link.prog)
447 			continue;
448 		/* prog already linked */
449 		return -EBUSY;
450 	}
451 
452 	hlist_add_head(&link->tramp_hlist, &tr->progs_hlist[kind]);
453 	tr->progs_cnt[kind]++;
454 	err = bpf_trampoline_update(tr);
455 	if (err) {
456 		hlist_del_init(&link->tramp_hlist);
457 		tr->progs_cnt[kind]--;
458 	}
459 	return err;
460 }
461 
462 int bpf_trampoline_link_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr)
463 {
464 	int err;
465 
466 	mutex_lock(&tr->mutex);
467 	err = __bpf_trampoline_link_prog(link, tr);
468 	mutex_unlock(&tr->mutex);
469 	return err;
470 }
471 
472 static int __bpf_trampoline_unlink_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr)
473 {
474 	enum bpf_tramp_prog_type kind;
475 	int err;
476 
477 	kind = bpf_attach_type_to_tramp(link->link.prog);
478 	if (kind == BPF_TRAMP_REPLACE) {
479 		WARN_ON_ONCE(!tr->extension_prog);
480 		err = bpf_arch_text_poke(tr->func.addr, BPF_MOD_JUMP,
481 					 tr->extension_prog->bpf_func, NULL);
482 		tr->extension_prog = NULL;
483 		return err;
484 	}
485 	hlist_del_init(&link->tramp_hlist);
486 	tr->progs_cnt[kind]--;
487 	return bpf_trampoline_update(tr);
488 }
489 
490 /* bpf_trampoline_unlink_prog() should never fail. */
491 int bpf_trampoline_unlink_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr)
492 {
493 	int err;
494 
495 	mutex_lock(&tr->mutex);
496 	err = __bpf_trampoline_unlink_prog(link, tr);
497 	mutex_unlock(&tr->mutex);
498 	return err;
499 }
500 
501 #if defined(CONFIG_BPF_JIT) && defined(CONFIG_BPF_SYSCALL)
502 static void bpf_shim_tramp_link_release(struct bpf_link *link)
503 {
504 	struct bpf_shim_tramp_link *shim_link =
505 		container_of(link, struct bpf_shim_tramp_link, link.link);
506 
507 	/* paired with 'shim_link->trampoline = tr' in bpf_trampoline_link_cgroup_shim */
508 	if (!shim_link->trampoline)
509 		return;
510 
511 	WARN_ON_ONCE(bpf_trampoline_unlink_prog(&shim_link->link, shim_link->trampoline));
512 	bpf_trampoline_put(shim_link->trampoline);
513 }
514 
515 static void bpf_shim_tramp_link_dealloc(struct bpf_link *link)
516 {
517 	struct bpf_shim_tramp_link *shim_link =
518 		container_of(link, struct bpf_shim_tramp_link, link.link);
519 
520 	kfree(shim_link);
521 }
522 
523 static const struct bpf_link_ops bpf_shim_tramp_link_lops = {
524 	.release = bpf_shim_tramp_link_release,
525 	.dealloc = bpf_shim_tramp_link_dealloc,
526 };
527 
528 static struct bpf_shim_tramp_link *cgroup_shim_alloc(const struct bpf_prog *prog,
529 						     bpf_func_t bpf_func,
530 						     int cgroup_atype)
531 {
532 	struct bpf_shim_tramp_link *shim_link = NULL;
533 	struct bpf_prog *p;
534 
535 	shim_link = kzalloc(sizeof(*shim_link), GFP_USER);
536 	if (!shim_link)
537 		return NULL;
538 
539 	p = bpf_prog_alloc(1, 0);
540 	if (!p) {
541 		kfree(shim_link);
542 		return NULL;
543 	}
544 
545 	p->jited = false;
546 	p->bpf_func = bpf_func;
547 
548 	p->aux->cgroup_atype = cgroup_atype;
549 	p->aux->attach_func_proto = prog->aux->attach_func_proto;
550 	p->aux->attach_btf_id = prog->aux->attach_btf_id;
551 	p->aux->attach_btf = prog->aux->attach_btf;
552 	btf_get(p->aux->attach_btf);
553 	p->type = BPF_PROG_TYPE_LSM;
554 	p->expected_attach_type = BPF_LSM_MAC;
555 	bpf_prog_inc(p);
556 	bpf_link_init(&shim_link->link.link, BPF_LINK_TYPE_UNSPEC,
557 		      &bpf_shim_tramp_link_lops, p);
558 	bpf_cgroup_atype_get(p->aux->attach_btf_id, cgroup_atype);
559 
560 	return shim_link;
561 }
562 
563 static struct bpf_shim_tramp_link *cgroup_shim_find(struct bpf_trampoline *tr,
564 						    bpf_func_t bpf_func)
565 {
566 	struct bpf_tramp_link *link;
567 	int kind;
568 
569 	for (kind = 0; kind < BPF_TRAMP_MAX; kind++) {
570 		hlist_for_each_entry(link, &tr->progs_hlist[kind], tramp_hlist) {
571 			struct bpf_prog *p = link->link.prog;
572 
573 			if (p->bpf_func == bpf_func)
574 				return container_of(link, struct bpf_shim_tramp_link, link);
575 		}
576 	}
577 
578 	return NULL;
579 }
580 
581 int bpf_trampoline_link_cgroup_shim(struct bpf_prog *prog,
582 				    int cgroup_atype)
583 {
584 	struct bpf_shim_tramp_link *shim_link = NULL;
585 	struct bpf_attach_target_info tgt_info = {};
586 	struct bpf_trampoline *tr;
587 	bpf_func_t bpf_func;
588 	u64 key;
589 	int err;
590 
591 	err = bpf_check_attach_target(NULL, prog, NULL,
592 				      prog->aux->attach_btf_id,
593 				      &tgt_info);
594 	if (err)
595 		return err;
596 
597 	key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf,
598 					 prog->aux->attach_btf_id);
599 
600 	bpf_lsm_find_cgroup_shim(prog, &bpf_func);
601 	tr = bpf_trampoline_get(key, &tgt_info);
602 	if (!tr)
603 		return  -ENOMEM;
604 
605 	mutex_lock(&tr->mutex);
606 
607 	shim_link = cgroup_shim_find(tr, bpf_func);
608 	if (shim_link) {
609 		/* Reusing existing shim attached by the other program. */
610 		bpf_link_inc(&shim_link->link.link);
611 
612 		mutex_unlock(&tr->mutex);
613 		bpf_trampoline_put(tr); /* bpf_trampoline_get above */
614 		return 0;
615 	}
616 
617 	/* Allocate and install new shim. */
618 
619 	shim_link = cgroup_shim_alloc(prog, bpf_func, cgroup_atype);
620 	if (!shim_link) {
621 		err = -ENOMEM;
622 		goto err;
623 	}
624 
625 	err = __bpf_trampoline_link_prog(&shim_link->link, tr);
626 	if (err)
627 		goto err;
628 
629 	shim_link->trampoline = tr;
630 	/* note, we're still holding tr refcnt from above */
631 
632 	mutex_unlock(&tr->mutex);
633 
634 	return 0;
635 err:
636 	mutex_unlock(&tr->mutex);
637 
638 	if (shim_link)
639 		bpf_link_put(&shim_link->link.link);
640 
641 	/* have to release tr while _not_ holding its mutex */
642 	bpf_trampoline_put(tr); /* bpf_trampoline_get above */
643 
644 	return err;
645 }
646 
647 void bpf_trampoline_unlink_cgroup_shim(struct bpf_prog *prog)
648 {
649 	struct bpf_shim_tramp_link *shim_link = NULL;
650 	struct bpf_trampoline *tr;
651 	bpf_func_t bpf_func;
652 	u64 key;
653 
654 	key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf,
655 					 prog->aux->attach_btf_id);
656 
657 	bpf_lsm_find_cgroup_shim(prog, &bpf_func);
658 	tr = bpf_trampoline_lookup(key);
659 	if (WARN_ON_ONCE(!tr))
660 		return;
661 
662 	mutex_lock(&tr->mutex);
663 	shim_link = cgroup_shim_find(tr, bpf_func);
664 	mutex_unlock(&tr->mutex);
665 
666 	if (shim_link)
667 		bpf_link_put(&shim_link->link.link);
668 
669 	bpf_trampoline_put(tr); /* bpf_trampoline_lookup above */
670 }
671 #endif
672 
673 struct bpf_trampoline *bpf_trampoline_get(u64 key,
674 					  struct bpf_attach_target_info *tgt_info)
675 {
676 	struct bpf_trampoline *tr;
677 
678 	tr = bpf_trampoline_lookup(key);
679 	if (!tr)
680 		return NULL;
681 
682 	mutex_lock(&tr->mutex);
683 	if (tr->func.addr)
684 		goto out;
685 
686 	memcpy(&tr->func.model, &tgt_info->fmodel, sizeof(tgt_info->fmodel));
687 	tr->func.addr = (void *)tgt_info->tgt_addr;
688 out:
689 	mutex_unlock(&tr->mutex);
690 	return tr;
691 }
692 
693 void bpf_trampoline_put(struct bpf_trampoline *tr)
694 {
695 	int i;
696 
697 	if (!tr)
698 		return;
699 	mutex_lock(&trampoline_mutex);
700 	if (!refcount_dec_and_test(&tr->refcnt))
701 		goto out;
702 	WARN_ON_ONCE(mutex_is_locked(&tr->mutex));
703 
704 	for (i = 0; i < BPF_TRAMP_MAX; i++)
705 		if (WARN_ON_ONCE(!hlist_empty(&tr->progs_hlist[i])))
706 			goto out;
707 
708 	/* This code will be executed even when the last bpf_tramp_image
709 	 * is alive. All progs are detached from the trampoline and the
710 	 * trampoline image is patched with jmp into epilogue to skip
711 	 * fexit progs. The fentry-only trampoline will be freed via
712 	 * multiple rcu callbacks.
713 	 */
714 	hlist_del(&tr->hlist);
715 	kfree(tr);
716 out:
717 	mutex_unlock(&trampoline_mutex);
718 }
719 
720 #define NO_START_TIME 1
721 static __always_inline u64 notrace bpf_prog_start_time(void)
722 {
723 	u64 start = NO_START_TIME;
724 
725 	if (static_branch_unlikely(&bpf_stats_enabled_key)) {
726 		start = sched_clock();
727 		if (unlikely(!start))
728 			start = NO_START_TIME;
729 	}
730 	return start;
731 }
732 
733 static void notrace inc_misses_counter(struct bpf_prog *prog)
734 {
735 	struct bpf_prog_stats *stats;
736 	unsigned int flags;
737 
738 	stats = this_cpu_ptr(prog->stats);
739 	flags = u64_stats_update_begin_irqsave(&stats->syncp);
740 	u64_stats_inc(&stats->misses);
741 	u64_stats_update_end_irqrestore(&stats->syncp, flags);
742 }
743 
744 /* The logic is similar to bpf_prog_run(), but with an explicit
745  * rcu_read_lock() and migrate_disable() which are required
746  * for the trampoline. The macro is split into
747  * call __bpf_prog_enter
748  * call prog->bpf_func
749  * call __bpf_prog_exit
750  *
751  * __bpf_prog_enter returns:
752  * 0 - skip execution of the bpf prog
753  * 1 - execute bpf prog
754  * [2..MAX_U64] - execute bpf prog and record execution time.
755  *     This is start time.
756  */
757 u64 notrace __bpf_prog_enter(struct bpf_prog *prog, struct bpf_tramp_run_ctx *run_ctx)
758 	__acquires(RCU)
759 {
760 	rcu_read_lock();
761 	migrate_disable();
762 
763 	run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
764 
765 	if (unlikely(__this_cpu_inc_return(*(prog->active)) != 1)) {
766 		inc_misses_counter(prog);
767 		return 0;
768 	}
769 	return bpf_prog_start_time();
770 }
771 
772 static void notrace update_prog_stats(struct bpf_prog *prog,
773 				      u64 start)
774 {
775 	struct bpf_prog_stats *stats;
776 
777 	if (static_branch_unlikely(&bpf_stats_enabled_key) &&
778 	    /* static_key could be enabled in __bpf_prog_enter*
779 	     * and disabled in __bpf_prog_exit*.
780 	     * And vice versa.
781 	     * Hence check that 'start' is valid.
782 	     */
783 	    start > NO_START_TIME) {
784 		unsigned long flags;
785 
786 		stats = this_cpu_ptr(prog->stats);
787 		flags = u64_stats_update_begin_irqsave(&stats->syncp);
788 		u64_stats_inc(&stats->cnt);
789 		u64_stats_add(&stats->nsecs, sched_clock() - start);
790 		u64_stats_update_end_irqrestore(&stats->syncp, flags);
791 	}
792 }
793 
794 void notrace __bpf_prog_exit(struct bpf_prog *prog, u64 start, struct bpf_tramp_run_ctx *run_ctx)
795 	__releases(RCU)
796 {
797 	bpf_reset_run_ctx(run_ctx->saved_run_ctx);
798 
799 	update_prog_stats(prog, start);
800 	__this_cpu_dec(*(prog->active));
801 	migrate_enable();
802 	rcu_read_unlock();
803 }
804 
805 u64 notrace __bpf_prog_enter_lsm_cgroup(struct bpf_prog *prog,
806 					struct bpf_tramp_run_ctx *run_ctx)
807 	__acquires(RCU)
808 {
809 	/* Runtime stats are exported via actual BPF_LSM_CGROUP
810 	 * programs, not the shims.
811 	 */
812 	rcu_read_lock();
813 	migrate_disable();
814 
815 	run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
816 
817 	return NO_START_TIME;
818 }
819 
820 void notrace __bpf_prog_exit_lsm_cgroup(struct bpf_prog *prog, u64 start,
821 					struct bpf_tramp_run_ctx *run_ctx)
822 	__releases(RCU)
823 {
824 	bpf_reset_run_ctx(run_ctx->saved_run_ctx);
825 
826 	migrate_enable();
827 	rcu_read_unlock();
828 }
829 
830 u64 notrace __bpf_prog_enter_sleepable(struct bpf_prog *prog, struct bpf_tramp_run_ctx *run_ctx)
831 {
832 	rcu_read_lock_trace();
833 	migrate_disable();
834 	might_fault();
835 
836 	if (unlikely(__this_cpu_inc_return(*(prog->active)) != 1)) {
837 		inc_misses_counter(prog);
838 		return 0;
839 	}
840 
841 	run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
842 
843 	return bpf_prog_start_time();
844 }
845 
846 void notrace __bpf_prog_exit_sleepable(struct bpf_prog *prog, u64 start,
847 				       struct bpf_tramp_run_ctx *run_ctx)
848 {
849 	bpf_reset_run_ctx(run_ctx->saved_run_ctx);
850 
851 	update_prog_stats(prog, start);
852 	__this_cpu_dec(*(prog->active));
853 	migrate_enable();
854 	rcu_read_unlock_trace();
855 }
856 
857 void notrace __bpf_tramp_enter(struct bpf_tramp_image *tr)
858 {
859 	percpu_ref_get(&tr->pcref);
860 }
861 
862 void notrace __bpf_tramp_exit(struct bpf_tramp_image *tr)
863 {
864 	percpu_ref_put(&tr->pcref);
865 }
866 
867 int __weak
868 arch_prepare_bpf_trampoline(struct bpf_tramp_image *tr, void *image, void *image_end,
869 			    const struct btf_func_model *m, u32 flags,
870 			    struct bpf_tramp_links *tlinks,
871 			    void *orig_call)
872 {
873 	return -ENOTSUPP;
874 }
875 
876 static int __init init_trampolines(void)
877 {
878 	int i;
879 
880 	for (i = 0; i < TRAMPOLINE_TABLE_SIZE; i++)
881 		INIT_HLIST_HEAD(&trampoline_table[i]);
882 	return 0;
883 }
884 late_initcall(init_trampolines);
885