xref: /linux/kernel/bpf/trampoline.c (revision 424f6a3610965d125634bc65c5d6d506582d4f7e)
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/static_call.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/bpf_lsm.h>
15 #include <linux/delay.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_key_table[TRAMPOLINE_TABLE_SIZE];
28 static struct hlist_head trampoline_ip_table[TRAMPOLINE_TABLE_SIZE];
29 
30 /* serializes access to trampoline tables */
31 static DEFINE_MUTEX(trampoline_mutex);
32 
33 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
34 static int bpf_trampoline_update(struct bpf_trampoline *tr, bool lock_direct_mutex);
35 
36 #ifdef CONFIG_HAVE_SINGLE_FTRACE_DIRECT_OPS
37 static struct bpf_trampoline *direct_ops_ip_lookup(struct ftrace_ops *ops, unsigned long ip)
38 {
39 	struct hlist_head *head_ip;
40 	struct bpf_trampoline *tr;
41 
42 	mutex_lock(&trampoline_mutex);
43 	head_ip = &trampoline_ip_table[hash_64(ip, TRAMPOLINE_HASH_BITS)];
44 	hlist_for_each_entry(tr, head_ip, hlist_ip) {
45 		if (tr->ip == ip)
46 			goto out;
47 	}
48 	tr = NULL;
49 out:
50 	mutex_unlock(&trampoline_mutex);
51 	return tr;
52 }
53 #else
54 static struct bpf_trampoline *direct_ops_ip_lookup(struct ftrace_ops *ops, unsigned long ip)
55 {
56 	return ops->private;
57 }
58 #endif /* CONFIG_HAVE_SINGLE_FTRACE_DIRECT_OPS */
59 
60 static int bpf_tramp_ftrace_ops_func(struct ftrace_ops *ops, unsigned long ip,
61 				     enum ftrace_ops_cmd cmd)
62 {
63 	struct bpf_trampoline *tr;
64 	int ret = 0;
65 
66 	tr = direct_ops_ip_lookup(ops, ip);
67 	if (!tr)
68 		return -EINVAL;
69 
70 	if (cmd == FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_SELF) {
71 		/* This is called inside register_ftrace_direct_multi(), so
72 		 * tr->mutex is already locked.
73 		 */
74 		lockdep_assert_held_once(&tr->mutex);
75 
76 		/* Instead of updating the trampoline here, we propagate
77 		 * -EAGAIN to register_ftrace_direct(). Then we can
78 		 * retry register_ftrace_direct() after updating the
79 		 * trampoline.
80 		 */
81 		if ((tr->flags & BPF_TRAMP_F_CALL_ORIG) &&
82 		    !(tr->flags & BPF_TRAMP_F_ORIG_STACK)) {
83 			if (WARN_ON_ONCE(tr->flags & BPF_TRAMP_F_SHARE_IPMODIFY))
84 				return -EBUSY;
85 
86 			tr->flags |= BPF_TRAMP_F_SHARE_IPMODIFY;
87 			return -EAGAIN;
88 		}
89 
90 		return 0;
91 	}
92 
93 	/* The normal locking order is
94 	 *    tr->mutex => direct_mutex (ftrace.c) => ftrace_lock (ftrace.c)
95 	 *
96 	 * The following two commands are called from
97 	 *
98 	 *   prepare_direct_functions_for_ipmodify
99 	 *   cleanup_direct_functions_after_ipmodify
100 	 *
101 	 * In both cases, direct_mutex is already locked. Use
102 	 * mutex_trylock(&tr->mutex) to avoid deadlock in race condition
103 	 * (something else is making changes to this same trampoline).
104 	 */
105 	if (!mutex_trylock(&tr->mutex)) {
106 		/* sleep 1 ms to make sure whatever holding tr->mutex makes
107 		 * some progress.
108 		 */
109 		msleep(1);
110 		return -EAGAIN;
111 	}
112 
113 	switch (cmd) {
114 	case FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER:
115 		tr->flags |= BPF_TRAMP_F_SHARE_IPMODIFY;
116 
117 		if ((tr->flags & BPF_TRAMP_F_CALL_ORIG) &&
118 		    !(tr->flags & BPF_TRAMP_F_ORIG_STACK))
119 			ret = bpf_trampoline_update(tr, false /* lock_direct_mutex */);
120 		break;
121 	case FTRACE_OPS_CMD_DISABLE_SHARE_IPMODIFY_PEER:
122 		tr->flags &= ~BPF_TRAMP_F_SHARE_IPMODIFY;
123 
124 		if (tr->flags & BPF_TRAMP_F_ORIG_STACK)
125 			ret = bpf_trampoline_update(tr, false /* lock_direct_mutex */);
126 		break;
127 	default:
128 		ret = -EINVAL;
129 		break;
130 	}
131 
132 	mutex_unlock(&tr->mutex);
133 	return ret;
134 }
135 #endif
136 
137 bool bpf_prog_has_trampoline(const struct bpf_prog *prog)
138 {
139 	enum bpf_attach_type eatype = prog->expected_attach_type;
140 	enum bpf_prog_type ptype = prog->type;
141 
142 	switch (ptype) {
143 	case BPF_PROG_TYPE_TRACING:
144 		if (eatype == BPF_TRACE_FENTRY || eatype == BPF_TRACE_FEXIT ||
145 		    eatype == BPF_MODIFY_RETURN || eatype == BPF_TRACE_FSESSION)
146 			return true;
147 		return false;
148 	case BPF_PROG_TYPE_LSM:
149 		return eatype == BPF_LSM_MAC;
150 	default:
151 		return false;
152 	}
153 }
154 
155 void bpf_image_ksym_init(void *data, unsigned int size, struct bpf_ksym *ksym)
156 {
157 	ksym->start = (unsigned long) data;
158 	ksym->end = ksym->start + size;
159 }
160 
161 void bpf_image_ksym_add(struct bpf_ksym *ksym)
162 {
163 	bpf_ksym_add(ksym);
164 	perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, ksym->start,
165 			   PAGE_SIZE, false, ksym->name);
166 }
167 
168 void bpf_image_ksym_del(struct bpf_ksym *ksym)
169 {
170 	bpf_ksym_del(ksym);
171 	perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, ksym->start,
172 			   PAGE_SIZE, true, ksym->name);
173 }
174 
175 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
176 #ifdef CONFIG_HAVE_SINGLE_FTRACE_DIRECT_OPS
177 /*
178  * We have only single direct_ops which contains all the direct call
179  * sites and is the only global ftrace_ops for all trampolines.
180  *
181  * We use 'update_ftrace_direct_*' api for attachment.
182  */
183 struct ftrace_ops direct_ops = {
184 	.ops_func = bpf_tramp_ftrace_ops_func,
185 };
186 
187 static int direct_ops_alloc(struct bpf_trampoline *tr)
188 {
189 	tr->fops = &direct_ops;
190 	return 0;
191 }
192 
193 static void direct_ops_free(struct bpf_trampoline *tr) { }
194 
195 static struct ftrace_hash *hash_from_ip(struct bpf_trampoline *tr, void *ptr)
196 {
197 	unsigned long ip, addr = (unsigned long) ptr;
198 	struct ftrace_hash *hash;
199 
200 	ip = ftrace_location(tr->ip);
201 	if (!ip)
202 		return NULL;
203 	hash = alloc_ftrace_hash(FTRACE_HASH_DEFAULT_BITS);
204 	if (!hash)
205 		return NULL;
206 	if (bpf_trampoline_use_jmp(tr->flags))
207 		addr = ftrace_jmp_set(addr);
208 	if (!add_ftrace_hash_entry_direct(hash, ip, addr)) {
209 		free_ftrace_hash(hash);
210 		return NULL;
211 	}
212 	return hash;
213 }
214 
215 static int direct_ops_add(struct bpf_trampoline *tr, void *addr)
216 {
217 	struct ftrace_hash *hash = hash_from_ip(tr, addr);
218 	int err;
219 
220 	if (!hash)
221 		return -ENOMEM;
222 	err = update_ftrace_direct_add(tr->fops, hash);
223 	free_ftrace_hash(hash);
224 	return err;
225 }
226 
227 static int direct_ops_del(struct bpf_trampoline *tr, void *addr)
228 {
229 	struct ftrace_hash *hash = hash_from_ip(tr, addr);
230 	int err;
231 
232 	if (!hash)
233 		return -ENOMEM;
234 	err = update_ftrace_direct_del(tr->fops, hash);
235 	free_ftrace_hash(hash);
236 	return err;
237 }
238 
239 static int direct_ops_mod(struct bpf_trampoline *tr, void *addr, bool lock_direct_mutex)
240 {
241 	struct ftrace_hash *hash = hash_from_ip(tr, addr);
242 	int err;
243 
244 	if (!hash)
245 		return -ENOMEM;
246 	err = update_ftrace_direct_mod(tr->fops, hash, lock_direct_mutex);
247 	free_ftrace_hash(hash);
248 	return err;
249 }
250 #else
251 /*
252  * We allocate ftrace_ops object for each trampoline and it contains
253  * call site specific for that trampoline.
254  *
255  * We use *_ftrace_direct api for attachment.
256  */
257 static int direct_ops_alloc(struct bpf_trampoline *tr)
258 {
259 	tr->fops = kzalloc(sizeof(struct ftrace_ops), GFP_KERNEL);
260 	if (!tr->fops)
261 		return -ENOMEM;
262 	tr->fops->private = tr;
263 	tr->fops->ops_func = bpf_tramp_ftrace_ops_func;
264 	return 0;
265 }
266 
267 static void direct_ops_free(struct bpf_trampoline *tr)
268 {
269 	if (!tr->fops)
270 		return;
271 	ftrace_free_filter(tr->fops);
272 	kfree(tr->fops);
273 }
274 
275 static int direct_ops_add(struct bpf_trampoline *tr, void *ptr)
276 {
277 	unsigned long addr = (unsigned long) ptr;
278 	struct ftrace_ops *ops = tr->fops;
279 	int ret;
280 
281 	if (bpf_trampoline_use_jmp(tr->flags))
282 		addr = ftrace_jmp_set(addr);
283 
284 	ret = ftrace_set_filter_ip(ops, tr->ip, 0, 1);
285 	if (ret)
286 		return ret;
287 	return register_ftrace_direct(ops, addr);
288 }
289 
290 static int direct_ops_del(struct bpf_trampoline *tr, void *addr)
291 {
292 	return unregister_ftrace_direct(tr->fops, (long)addr, false);
293 }
294 
295 static int direct_ops_mod(struct bpf_trampoline *tr, void *ptr, bool lock_direct_mutex)
296 {
297 	unsigned long addr = (unsigned long) ptr;
298 	struct ftrace_ops *ops = tr->fops;
299 
300 	if (bpf_trampoline_use_jmp(tr->flags))
301 		addr = ftrace_jmp_set(addr);
302 	if (lock_direct_mutex)
303 		return modify_ftrace_direct(ops, addr);
304 	return modify_ftrace_direct_nolock(ops, addr);
305 }
306 #endif /* CONFIG_HAVE_SINGLE_FTRACE_DIRECT_OPS */
307 #else
308 static void direct_ops_free(struct bpf_trampoline *tr) { }
309 
310 static int direct_ops_alloc(struct bpf_trampoline *tr)
311 {
312 	return 0;
313 }
314 
315 static int direct_ops_add(struct bpf_trampoline *tr, void *addr)
316 {
317 	return -ENODEV;
318 }
319 
320 static int direct_ops_del(struct bpf_trampoline *tr, void *addr)
321 {
322 	return -ENODEV;
323 }
324 
325 static int direct_ops_mod(struct bpf_trampoline *tr, void *ptr, bool lock_direct_mutex)
326 {
327 	return -ENODEV;
328 }
329 #endif /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS */
330 
331 static struct bpf_trampoline *bpf_trampoline_lookup(u64 key, unsigned long ip)
332 {
333 	struct bpf_trampoline *tr;
334 	struct hlist_head *head;
335 	int i;
336 
337 	mutex_lock(&trampoline_mutex);
338 	head = &trampoline_key_table[hash_64(key, TRAMPOLINE_HASH_BITS)];
339 	hlist_for_each_entry(tr, head, hlist_key) {
340 		if (tr->key == key) {
341 			refcount_inc(&tr->refcnt);
342 			goto out;
343 		}
344 	}
345 	tr = kzalloc(sizeof(*tr), GFP_KERNEL);
346 	if (!tr)
347 		goto out;
348 	if (direct_ops_alloc(tr)) {
349 		kfree(tr);
350 		tr = NULL;
351 		goto out;
352 	}
353 
354 	tr->key = key;
355 	tr->ip = ftrace_location(ip);
356 	INIT_HLIST_NODE(&tr->hlist_key);
357 	INIT_HLIST_NODE(&tr->hlist_ip);
358 	hlist_add_head(&tr->hlist_key, head);
359 	head = &trampoline_ip_table[hash_64(tr->ip, TRAMPOLINE_HASH_BITS)];
360 	hlist_add_head(&tr->hlist_ip, head);
361 	refcount_set(&tr->refcnt, 1);
362 	mutex_init(&tr->mutex);
363 	for (i = 0; i < BPF_TRAMP_MAX; i++)
364 		INIT_HLIST_HEAD(&tr->progs_hlist[i]);
365 out:
366 	mutex_unlock(&trampoline_mutex);
367 	return tr;
368 }
369 
370 static int bpf_trampoline_update_fentry(struct bpf_trampoline *tr, u32 orig_flags,
371 					void *old_addr, void *new_addr)
372 {
373 	enum bpf_text_poke_type new_t = BPF_MOD_CALL, old_t = BPF_MOD_CALL;
374 	void *ip = tr->func.addr;
375 
376 	if (!new_addr)
377 		new_t = BPF_MOD_NOP;
378 	else if (bpf_trampoline_use_jmp(tr->flags))
379 		new_t = BPF_MOD_JUMP;
380 
381 	if (!old_addr)
382 		old_t = BPF_MOD_NOP;
383 	else if (bpf_trampoline_use_jmp(orig_flags))
384 		old_t = BPF_MOD_JUMP;
385 
386 	return bpf_arch_text_poke(ip, old_t, new_t, old_addr, new_addr);
387 }
388 
389 static int unregister_fentry(struct bpf_trampoline *tr, u32 orig_flags,
390 			     void *old_addr)
391 {
392 	int ret;
393 
394 	if (tr->func.ftrace_managed)
395 		ret = direct_ops_del(tr, old_addr);
396 	else
397 		ret = bpf_trampoline_update_fentry(tr, orig_flags, old_addr, NULL);
398 
399 	return ret;
400 }
401 
402 static int modify_fentry(struct bpf_trampoline *tr, u32 orig_flags,
403 			 void *old_addr, void *new_addr,
404 			 bool lock_direct_mutex)
405 {
406 	int ret;
407 
408 	if (tr->func.ftrace_managed) {
409 		ret = direct_ops_mod(tr, new_addr, lock_direct_mutex);
410 	} else {
411 		ret = bpf_trampoline_update_fentry(tr, orig_flags, old_addr,
412 						   new_addr);
413 	}
414 	return ret;
415 }
416 
417 /* first time registering */
418 static int register_fentry(struct bpf_trampoline *tr, void *new_addr)
419 {
420 	void *ip = tr->func.addr;
421 	unsigned long faddr;
422 	int ret;
423 
424 	faddr = ftrace_location((unsigned long)ip);
425 	if (faddr) {
426 		if (!tr->fops)
427 			return -ENOTSUPP;
428 		tr->func.ftrace_managed = true;
429 	}
430 
431 	if (tr->func.ftrace_managed) {
432 		ret = direct_ops_add(tr, new_addr);
433 	} else {
434 		ret = bpf_trampoline_update_fentry(tr, 0, NULL, new_addr);
435 	}
436 
437 	return ret;
438 }
439 
440 static struct bpf_tramp_links *
441 bpf_trampoline_get_progs(const struct bpf_trampoline *tr, int *total, bool *ip_arg)
442 {
443 	struct bpf_tramp_link *link;
444 	struct bpf_tramp_links *tlinks;
445 	struct bpf_tramp_link **links;
446 	int kind;
447 
448 	*total = 0;
449 	tlinks = kcalloc(BPF_TRAMP_MAX, sizeof(*tlinks), GFP_KERNEL);
450 	if (!tlinks)
451 		return ERR_PTR(-ENOMEM);
452 
453 	for (kind = 0; kind < BPF_TRAMP_MAX; kind++) {
454 		tlinks[kind].nr_links = tr->progs_cnt[kind];
455 		*total += tr->progs_cnt[kind];
456 		links = tlinks[kind].links;
457 
458 		hlist_for_each_entry(link, &tr->progs_hlist[kind], tramp_hlist) {
459 			*ip_arg |= link->link.prog->call_get_func_ip;
460 			*links++ = link;
461 		}
462 	}
463 	return tlinks;
464 }
465 
466 static void bpf_tramp_image_free(struct bpf_tramp_image *im)
467 {
468 	bpf_image_ksym_del(&im->ksym);
469 	arch_free_bpf_trampoline(im->image, im->size);
470 	bpf_jit_uncharge_modmem(im->size);
471 	percpu_ref_exit(&im->pcref);
472 	kfree_rcu(im, rcu);
473 }
474 
475 static void __bpf_tramp_image_put_deferred(struct work_struct *work)
476 {
477 	struct bpf_tramp_image *im;
478 
479 	im = container_of(work, struct bpf_tramp_image, work);
480 	bpf_tramp_image_free(im);
481 }
482 
483 /* callback, fexit step 3 or fentry step 2 */
484 static void __bpf_tramp_image_put_rcu(struct rcu_head *rcu)
485 {
486 	struct bpf_tramp_image *im;
487 
488 	im = container_of(rcu, struct bpf_tramp_image, rcu);
489 	INIT_WORK(&im->work, __bpf_tramp_image_put_deferred);
490 	schedule_work(&im->work);
491 }
492 
493 /* callback, fexit step 2. Called after percpu_ref_kill confirms. */
494 static void __bpf_tramp_image_release(struct percpu_ref *pcref)
495 {
496 	struct bpf_tramp_image *im;
497 
498 	im = container_of(pcref, struct bpf_tramp_image, pcref);
499 	call_rcu_tasks(&im->rcu, __bpf_tramp_image_put_rcu);
500 }
501 
502 /* callback, fexit or fentry step 1 */
503 static void __bpf_tramp_image_put_rcu_tasks(struct rcu_head *rcu)
504 {
505 	struct bpf_tramp_image *im;
506 
507 	im = container_of(rcu, struct bpf_tramp_image, rcu);
508 	if (im->ip_after_call)
509 		/* the case of fmod_ret/fexit trampoline and CONFIG_PREEMPTION=y */
510 		percpu_ref_kill(&im->pcref);
511 	else
512 		/* the case of fentry trampoline */
513 		call_rcu_tasks(&im->rcu, __bpf_tramp_image_put_rcu);
514 }
515 
516 static void bpf_tramp_image_put(struct bpf_tramp_image *im)
517 {
518 	/* The trampoline image that calls original function is using:
519 	 * rcu_read_lock_trace to protect sleepable bpf progs
520 	 * rcu_read_lock to protect normal bpf progs
521 	 * percpu_ref to protect trampoline itself
522 	 * rcu tasks to protect trampoline asm not covered by percpu_ref
523 	 * (which are few asm insns before __bpf_tramp_enter and
524 	 *  after __bpf_tramp_exit)
525 	 *
526 	 * The trampoline is unreachable before bpf_tramp_image_put().
527 	 *
528 	 * First, patch the trampoline to avoid calling into fexit progs.
529 	 * The progs will be freed even if the original function is still
530 	 * executing or sleeping.
531 	 * In case of CONFIG_PREEMPT=y use call_rcu_tasks() to wait on
532 	 * first few asm instructions to execute and call into
533 	 * __bpf_tramp_enter->percpu_ref_get.
534 	 * Then use percpu_ref_kill to wait for the trampoline and the original
535 	 * function to finish.
536 	 * Then use call_rcu_tasks() to make sure few asm insns in
537 	 * the trampoline epilogue are done as well.
538 	 *
539 	 * In !PREEMPT case the task that got interrupted in the first asm
540 	 * insns won't go through an RCU quiescent state which the
541 	 * percpu_ref_kill will be waiting for. Hence the first
542 	 * call_rcu_tasks() is not necessary.
543 	 */
544 	if (im->ip_after_call) {
545 		int err = bpf_arch_text_poke(im->ip_after_call, BPF_MOD_NOP,
546 					     BPF_MOD_JUMP, NULL,
547 					     im->ip_epilogue);
548 		WARN_ON(err);
549 		if (IS_ENABLED(CONFIG_TASKS_RCU))
550 			call_rcu_tasks(&im->rcu, __bpf_tramp_image_put_rcu_tasks);
551 		else
552 			percpu_ref_kill(&im->pcref);
553 		return;
554 	}
555 
556 	/* The trampoline without fexit and fmod_ret progs doesn't call original
557 	 * function and doesn't use percpu_ref.
558 	 * Use call_rcu_tasks_trace() to wait for sleepable progs to finish.
559 	 * Then use call_rcu_tasks() to wait for the rest of trampoline asm
560 	 * and normal progs.
561 	 */
562 	call_rcu_tasks_trace(&im->rcu, __bpf_tramp_image_put_rcu_tasks);
563 }
564 
565 static struct bpf_tramp_image *bpf_tramp_image_alloc(u64 key, int size)
566 {
567 	struct bpf_tramp_image *im;
568 	struct bpf_ksym *ksym;
569 	void *image;
570 	int err = -ENOMEM;
571 
572 	im = kzalloc(sizeof(*im), GFP_KERNEL);
573 	if (!im)
574 		goto out;
575 
576 	err = bpf_jit_charge_modmem(size);
577 	if (err)
578 		goto out_free_im;
579 	im->size = size;
580 
581 	err = -ENOMEM;
582 	im->image = image = arch_alloc_bpf_trampoline(size);
583 	if (!image)
584 		goto out_uncharge;
585 
586 	err = percpu_ref_init(&im->pcref, __bpf_tramp_image_release, 0, GFP_KERNEL);
587 	if (err)
588 		goto out_free_image;
589 
590 	ksym = &im->ksym;
591 	INIT_LIST_HEAD_RCU(&ksym->lnode);
592 	snprintf(ksym->name, KSYM_NAME_LEN, "bpf_trampoline_%llu", key);
593 	bpf_image_ksym_init(image, size, ksym);
594 	bpf_image_ksym_add(ksym);
595 	return im;
596 
597 out_free_image:
598 	arch_free_bpf_trampoline(im->image, im->size);
599 out_uncharge:
600 	bpf_jit_uncharge_modmem(size);
601 out_free_im:
602 	kfree(im);
603 out:
604 	return ERR_PTR(err);
605 }
606 
607 static int bpf_trampoline_update(struct bpf_trampoline *tr, bool lock_direct_mutex)
608 {
609 	struct bpf_tramp_image *im;
610 	struct bpf_tramp_links *tlinks;
611 	u32 orig_flags = tr->flags;
612 	bool ip_arg = false;
613 	int err, total, size;
614 
615 	tlinks = bpf_trampoline_get_progs(tr, &total, &ip_arg);
616 	if (IS_ERR(tlinks))
617 		return PTR_ERR(tlinks);
618 
619 	if (total == 0) {
620 		err = unregister_fentry(tr, orig_flags, tr->cur_image->image);
621 		bpf_tramp_image_put(tr->cur_image);
622 		tr->cur_image = NULL;
623 		goto out;
624 	}
625 
626 	/* clear all bits except SHARE_IPMODIFY and TAIL_CALL_CTX */
627 	tr->flags &= (BPF_TRAMP_F_SHARE_IPMODIFY | BPF_TRAMP_F_TAIL_CALL_CTX);
628 
629 	if (tlinks[BPF_TRAMP_FEXIT].nr_links ||
630 	    tlinks[BPF_TRAMP_MODIFY_RETURN].nr_links) {
631 		/* NOTE: BPF_TRAMP_F_RESTORE_REGS and BPF_TRAMP_F_SKIP_FRAME
632 		 * should not be set together.
633 		 */
634 		tr->flags |= BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_SKIP_FRAME;
635 	} else {
636 		tr->flags |= BPF_TRAMP_F_RESTORE_REGS;
637 	}
638 
639 	if (ip_arg)
640 		tr->flags |= BPF_TRAMP_F_IP_ARG;
641 
642 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
643 again:
644 	if (tr->flags & BPF_TRAMP_F_CALL_ORIG) {
645 		if (tr->flags & BPF_TRAMP_F_SHARE_IPMODIFY) {
646 			/* The BPF_TRAMP_F_SKIP_FRAME can be cleared in the
647 			 * first try, reset it in the second try.
648 			 */
649 			tr->flags |= BPF_TRAMP_F_ORIG_STACK | BPF_TRAMP_F_SKIP_FRAME;
650 		} else if (IS_ENABLED(CONFIG_DYNAMIC_FTRACE_WITH_JMP)) {
651 			/* Use "jmp" instead of "call" for the trampoline
652 			 * in the origin call case, and we don't need to
653 			 * skip the frame.
654 			 */
655 			tr->flags &= ~BPF_TRAMP_F_SKIP_FRAME;
656 		}
657 	}
658 #endif
659 
660 	size = arch_bpf_trampoline_size(&tr->func.model, tr->flags,
661 					tlinks, tr->func.addr);
662 	if (size < 0) {
663 		err = size;
664 		goto out;
665 	}
666 
667 	if (size > PAGE_SIZE) {
668 		err = -E2BIG;
669 		goto out;
670 	}
671 
672 	im = bpf_tramp_image_alloc(tr->key, size);
673 	if (IS_ERR(im)) {
674 		err = PTR_ERR(im);
675 		goto out;
676 	}
677 
678 	err = arch_prepare_bpf_trampoline(im, im->image, im->image + size,
679 					  &tr->func.model, tr->flags, tlinks,
680 					  tr->func.addr);
681 	if (err < 0)
682 		goto out_free;
683 
684 	err = arch_protect_bpf_trampoline(im->image, im->size);
685 	if (err)
686 		goto out_free;
687 
688 	WARN_ON(tr->cur_image && total == 0);
689 	if (tr->cur_image)
690 		/* progs already running at this address */
691 		err = modify_fentry(tr, orig_flags, tr->cur_image->image,
692 				    im->image, lock_direct_mutex);
693 	else
694 		/* first time registering */
695 		err = register_fentry(tr, im->image);
696 
697 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
698 	if (err == -EAGAIN) {
699 		/* -EAGAIN from bpf_tramp_ftrace_ops_func. Now
700 		 * BPF_TRAMP_F_SHARE_IPMODIFY is set, we can generate the
701 		 * trampoline again, and retry register.
702 		 */
703 		bpf_tramp_image_free(im);
704 		goto again;
705 	}
706 #endif
707 	if (err)
708 		goto out_free;
709 
710 	if (tr->cur_image)
711 		bpf_tramp_image_put(tr->cur_image);
712 	tr->cur_image = im;
713 out:
714 	/* If any error happens, restore previous flags */
715 	if (err)
716 		tr->flags = orig_flags;
717 	kfree(tlinks);
718 	return err;
719 
720 out_free:
721 	bpf_tramp_image_free(im);
722 	goto out;
723 }
724 
725 static enum bpf_tramp_prog_type bpf_attach_type_to_tramp(struct bpf_prog *prog)
726 {
727 	switch (prog->expected_attach_type) {
728 	case BPF_TRACE_FENTRY:
729 		return BPF_TRAMP_FENTRY;
730 	case BPF_MODIFY_RETURN:
731 		return BPF_TRAMP_MODIFY_RETURN;
732 	case BPF_TRACE_FEXIT:
733 		return BPF_TRAMP_FEXIT;
734 	case BPF_TRACE_FSESSION:
735 		return BPF_TRAMP_FSESSION;
736 	case BPF_LSM_MAC:
737 		if (!prog->aux->attach_func_proto->type)
738 			/* The function returns void, we cannot modify its
739 			 * return value.
740 			 */
741 			return BPF_TRAMP_FEXIT;
742 		else
743 			return BPF_TRAMP_MODIFY_RETURN;
744 	default:
745 		return BPF_TRAMP_REPLACE;
746 	}
747 }
748 
749 static int bpf_freplace_check_tgt_prog(struct bpf_prog *tgt_prog)
750 {
751 	struct bpf_prog_aux *aux = tgt_prog->aux;
752 
753 	guard(mutex)(&aux->ext_mutex);
754 	if (aux->prog_array_member_cnt)
755 		/* Program extensions can not extend target prog when the target
756 		 * prog has been updated to any prog_array map as tail callee.
757 		 * It's to prevent a potential infinite loop like:
758 		 * tgt prog entry -> tgt prog subprog -> freplace prog entry
759 		 * --tailcall-> tgt prog entry.
760 		 */
761 		return -EBUSY;
762 
763 	aux->is_extended = true;
764 	return 0;
765 }
766 
767 static int __bpf_trampoline_link_prog(struct bpf_tramp_link *link,
768 				      struct bpf_trampoline *tr,
769 				      struct bpf_prog *tgt_prog)
770 {
771 	struct bpf_fsession_link *fslink = NULL;
772 	enum bpf_tramp_prog_type kind;
773 	struct bpf_tramp_link *link_exiting;
774 	struct hlist_head *prog_list;
775 	int err = 0;
776 	int cnt = 0, i;
777 
778 	kind = bpf_attach_type_to_tramp(link->link.prog);
779 	if (tr->extension_prog)
780 		/* cannot attach fentry/fexit if extension prog is attached.
781 		 * cannot overwrite extension prog either.
782 		 */
783 		return -EBUSY;
784 
785 	for (i = 0; i < BPF_TRAMP_MAX; i++)
786 		cnt += tr->progs_cnt[i];
787 
788 	if (kind == BPF_TRAMP_REPLACE) {
789 		/* Cannot attach extension if fentry/fexit are in use. */
790 		if (cnt)
791 			return -EBUSY;
792 		err = bpf_freplace_check_tgt_prog(tgt_prog);
793 		if (err)
794 			return err;
795 		tr->extension_prog = link->link.prog;
796 		return bpf_arch_text_poke(tr->func.addr, BPF_MOD_NOP,
797 					  BPF_MOD_JUMP, NULL,
798 					  link->link.prog->bpf_func);
799 	}
800 	if (kind == BPF_TRAMP_FSESSION) {
801 		prog_list = &tr->progs_hlist[BPF_TRAMP_FENTRY];
802 		cnt++;
803 	} else {
804 		prog_list = &tr->progs_hlist[kind];
805 	}
806 	if (cnt >= BPF_MAX_TRAMP_LINKS)
807 		return -E2BIG;
808 	if (!hlist_unhashed(&link->tramp_hlist))
809 		/* prog already linked */
810 		return -EBUSY;
811 	hlist_for_each_entry(link_exiting, prog_list, tramp_hlist) {
812 		if (link_exiting->link.prog != link->link.prog)
813 			continue;
814 		/* prog already linked */
815 		return -EBUSY;
816 	}
817 
818 	hlist_add_head(&link->tramp_hlist, prog_list);
819 	if (kind == BPF_TRAMP_FSESSION) {
820 		tr->progs_cnt[BPF_TRAMP_FENTRY]++;
821 		fslink = container_of(link, struct bpf_fsession_link, link.link);
822 		hlist_add_head(&fslink->fexit.tramp_hlist, &tr->progs_hlist[BPF_TRAMP_FEXIT]);
823 		tr->progs_cnt[BPF_TRAMP_FEXIT]++;
824 	} else {
825 		tr->progs_cnt[kind]++;
826 	}
827 	err = bpf_trampoline_update(tr, true /* lock_direct_mutex */);
828 	if (err) {
829 		hlist_del_init(&link->tramp_hlist);
830 		if (kind == BPF_TRAMP_FSESSION) {
831 			tr->progs_cnt[BPF_TRAMP_FENTRY]--;
832 			hlist_del_init(&fslink->fexit.tramp_hlist);
833 			tr->progs_cnt[BPF_TRAMP_FEXIT]--;
834 		} else {
835 			tr->progs_cnt[kind]--;
836 		}
837 	}
838 	return err;
839 }
840 
841 int bpf_trampoline_link_prog(struct bpf_tramp_link *link,
842 			     struct bpf_trampoline *tr,
843 			     struct bpf_prog *tgt_prog)
844 {
845 	int err;
846 
847 	mutex_lock(&tr->mutex);
848 	err = __bpf_trampoline_link_prog(link, tr, tgt_prog);
849 	mutex_unlock(&tr->mutex);
850 	return err;
851 }
852 
853 static int __bpf_trampoline_unlink_prog(struct bpf_tramp_link *link,
854 					struct bpf_trampoline *tr,
855 					struct bpf_prog *tgt_prog)
856 {
857 	enum bpf_tramp_prog_type kind;
858 	int err;
859 
860 	kind = bpf_attach_type_to_tramp(link->link.prog);
861 	if (kind == BPF_TRAMP_REPLACE) {
862 		WARN_ON_ONCE(!tr->extension_prog);
863 		err = bpf_arch_text_poke(tr->func.addr, BPF_MOD_JUMP,
864 					 BPF_MOD_NOP,
865 					 tr->extension_prog->bpf_func, NULL);
866 		tr->extension_prog = NULL;
867 		guard(mutex)(&tgt_prog->aux->ext_mutex);
868 		tgt_prog->aux->is_extended = false;
869 		return err;
870 	} else if (kind == BPF_TRAMP_FSESSION) {
871 		struct bpf_fsession_link *fslink =
872 			container_of(link, struct bpf_fsession_link, link.link);
873 
874 		hlist_del_init(&fslink->fexit.tramp_hlist);
875 		tr->progs_cnt[BPF_TRAMP_FEXIT]--;
876 		kind = BPF_TRAMP_FENTRY;
877 	}
878 	hlist_del_init(&link->tramp_hlist);
879 	tr->progs_cnt[kind]--;
880 	return bpf_trampoline_update(tr, true /* lock_direct_mutex */);
881 }
882 
883 /* bpf_trampoline_unlink_prog() should never fail. */
884 int bpf_trampoline_unlink_prog(struct bpf_tramp_link *link,
885 			       struct bpf_trampoline *tr,
886 			       struct bpf_prog *tgt_prog)
887 {
888 	int err;
889 
890 	mutex_lock(&tr->mutex);
891 	err = __bpf_trampoline_unlink_prog(link, tr, tgt_prog);
892 	mutex_unlock(&tr->mutex);
893 	return err;
894 }
895 
896 #if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_BPF_LSM)
897 static void bpf_shim_tramp_link_release(struct bpf_link *link)
898 {
899 	struct bpf_shim_tramp_link *shim_link =
900 		container_of(link, struct bpf_shim_tramp_link, link.link);
901 
902 	/* paired with 'shim_link->trampoline = tr' in bpf_trampoline_link_cgroup_shim */
903 	if (!shim_link->trampoline)
904 		return;
905 
906 	WARN_ON_ONCE(bpf_trampoline_unlink_prog(&shim_link->link, shim_link->trampoline, NULL));
907 	bpf_trampoline_put(shim_link->trampoline);
908 }
909 
910 static void bpf_shim_tramp_link_dealloc(struct bpf_link *link)
911 {
912 	struct bpf_shim_tramp_link *shim_link =
913 		container_of(link, struct bpf_shim_tramp_link, link.link);
914 
915 	kfree(shim_link);
916 }
917 
918 static const struct bpf_link_ops bpf_shim_tramp_link_lops = {
919 	.release = bpf_shim_tramp_link_release,
920 	.dealloc = bpf_shim_tramp_link_dealloc,
921 };
922 
923 static struct bpf_shim_tramp_link *cgroup_shim_alloc(const struct bpf_prog *prog,
924 						     bpf_func_t bpf_func,
925 						     int cgroup_atype,
926 						     enum bpf_attach_type attach_type)
927 {
928 	struct bpf_shim_tramp_link *shim_link = NULL;
929 	struct bpf_prog *p;
930 
931 	shim_link = kzalloc(sizeof(*shim_link), GFP_USER);
932 	if (!shim_link)
933 		return NULL;
934 
935 	p = bpf_prog_alloc(1, 0);
936 	if (!p) {
937 		kfree(shim_link);
938 		return NULL;
939 	}
940 
941 	p->jited = false;
942 	p->bpf_func = bpf_func;
943 
944 	p->aux->cgroup_atype = cgroup_atype;
945 	p->aux->attach_func_proto = prog->aux->attach_func_proto;
946 	p->aux->attach_btf_id = prog->aux->attach_btf_id;
947 	p->aux->attach_btf = prog->aux->attach_btf;
948 	btf_get(p->aux->attach_btf);
949 	p->type = BPF_PROG_TYPE_LSM;
950 	p->expected_attach_type = BPF_LSM_MAC;
951 	bpf_prog_inc(p);
952 	bpf_link_init(&shim_link->link.link, BPF_LINK_TYPE_UNSPEC,
953 		      &bpf_shim_tramp_link_lops, p, attach_type);
954 	bpf_cgroup_atype_get(p->aux->attach_btf_id, cgroup_atype);
955 
956 	return shim_link;
957 }
958 
959 static struct bpf_shim_tramp_link *cgroup_shim_find(struct bpf_trampoline *tr,
960 						    bpf_func_t bpf_func)
961 {
962 	struct bpf_tramp_link *link;
963 	int kind;
964 
965 	for (kind = 0; kind < BPF_TRAMP_MAX; kind++) {
966 		hlist_for_each_entry(link, &tr->progs_hlist[kind], tramp_hlist) {
967 			struct bpf_prog *p = link->link.prog;
968 
969 			if (p->bpf_func == bpf_func)
970 				return container_of(link, struct bpf_shim_tramp_link, link);
971 		}
972 	}
973 
974 	return NULL;
975 }
976 
977 int bpf_trampoline_link_cgroup_shim(struct bpf_prog *prog,
978 				    int cgroup_atype,
979 				    enum bpf_attach_type attach_type)
980 {
981 	struct bpf_shim_tramp_link *shim_link = NULL;
982 	struct bpf_attach_target_info tgt_info = {};
983 	struct bpf_trampoline *tr;
984 	bpf_func_t bpf_func;
985 	u64 key;
986 	int err;
987 
988 	err = bpf_check_attach_target(NULL, prog, NULL,
989 				      prog->aux->attach_btf_id,
990 				      &tgt_info);
991 	if (err)
992 		return err;
993 
994 	key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf,
995 					 prog->aux->attach_btf_id);
996 
997 	bpf_lsm_find_cgroup_shim(prog, &bpf_func);
998 	tr = bpf_trampoline_get(key, &tgt_info);
999 	if (!tr)
1000 		return  -ENOMEM;
1001 
1002 	mutex_lock(&tr->mutex);
1003 
1004 	shim_link = cgroup_shim_find(tr, bpf_func);
1005 	if (shim_link) {
1006 		/* Reusing existing shim attached by the other program. */
1007 		bpf_link_inc(&shim_link->link.link);
1008 
1009 		mutex_unlock(&tr->mutex);
1010 		bpf_trampoline_put(tr); /* bpf_trampoline_get above */
1011 		return 0;
1012 	}
1013 
1014 	/* Allocate and install new shim. */
1015 
1016 	shim_link = cgroup_shim_alloc(prog, bpf_func, cgroup_atype, attach_type);
1017 	if (!shim_link) {
1018 		err = -ENOMEM;
1019 		goto err;
1020 	}
1021 
1022 	err = __bpf_trampoline_link_prog(&shim_link->link, tr, NULL);
1023 	if (err)
1024 		goto err;
1025 
1026 	shim_link->trampoline = tr;
1027 	/* note, we're still holding tr refcnt from above */
1028 
1029 	mutex_unlock(&tr->mutex);
1030 
1031 	return 0;
1032 err:
1033 	mutex_unlock(&tr->mutex);
1034 
1035 	if (shim_link)
1036 		bpf_link_put(&shim_link->link.link);
1037 
1038 	/* have to release tr while _not_ holding its mutex */
1039 	bpf_trampoline_put(tr); /* bpf_trampoline_get above */
1040 
1041 	return err;
1042 }
1043 
1044 void bpf_trampoline_unlink_cgroup_shim(struct bpf_prog *prog)
1045 {
1046 	struct bpf_shim_tramp_link *shim_link = NULL;
1047 	struct bpf_trampoline *tr;
1048 	bpf_func_t bpf_func;
1049 	u64 key;
1050 
1051 	key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf,
1052 					 prog->aux->attach_btf_id);
1053 
1054 	bpf_lsm_find_cgroup_shim(prog, &bpf_func);
1055 	tr = bpf_trampoline_lookup(key, 0);
1056 	if (WARN_ON_ONCE(!tr))
1057 		return;
1058 
1059 	mutex_lock(&tr->mutex);
1060 	shim_link = cgroup_shim_find(tr, bpf_func);
1061 	mutex_unlock(&tr->mutex);
1062 
1063 	if (shim_link)
1064 		bpf_link_put(&shim_link->link.link);
1065 
1066 	bpf_trampoline_put(tr); /* bpf_trampoline_lookup above */
1067 }
1068 #endif
1069 
1070 struct bpf_trampoline *bpf_trampoline_get(u64 key,
1071 					  struct bpf_attach_target_info *tgt_info)
1072 {
1073 	struct bpf_trampoline *tr;
1074 
1075 	tr = bpf_trampoline_lookup(key, tgt_info->tgt_addr);
1076 	if (!tr)
1077 		return NULL;
1078 
1079 	mutex_lock(&tr->mutex);
1080 	if (tr->func.addr)
1081 		goto out;
1082 
1083 	memcpy(&tr->func.model, &tgt_info->fmodel, sizeof(tgt_info->fmodel));
1084 	tr->func.addr = (void *)tgt_info->tgt_addr;
1085 out:
1086 	mutex_unlock(&tr->mutex);
1087 	return tr;
1088 }
1089 
1090 void bpf_trampoline_put(struct bpf_trampoline *tr)
1091 {
1092 	int i;
1093 
1094 	if (!tr)
1095 		return;
1096 	mutex_lock(&trampoline_mutex);
1097 	if (!refcount_dec_and_test(&tr->refcnt))
1098 		goto out;
1099 	WARN_ON_ONCE(mutex_is_locked(&tr->mutex));
1100 
1101 	for (i = 0; i < BPF_TRAMP_MAX; i++)
1102 		if (WARN_ON_ONCE(!hlist_empty(&tr->progs_hlist[i])))
1103 			goto out;
1104 
1105 	/* This code will be executed even when the last bpf_tramp_image
1106 	 * is alive. All progs are detached from the trampoline and the
1107 	 * trampoline image is patched with jmp into epilogue to skip
1108 	 * fexit progs. The fentry-only trampoline will be freed via
1109 	 * multiple rcu callbacks.
1110 	 */
1111 	hlist_del(&tr->hlist_key);
1112 	hlist_del(&tr->hlist_ip);
1113 	direct_ops_free(tr);
1114 	kfree(tr);
1115 out:
1116 	mutex_unlock(&trampoline_mutex);
1117 }
1118 
1119 #define NO_START_TIME 1
1120 static __always_inline u64 notrace bpf_prog_start_time(void)
1121 {
1122 	u64 start = NO_START_TIME;
1123 
1124 	if (static_branch_unlikely(&bpf_stats_enabled_key)) {
1125 		start = sched_clock();
1126 		if (unlikely(!start))
1127 			start = NO_START_TIME;
1128 	}
1129 	return start;
1130 }
1131 
1132 /* The logic is similar to bpf_prog_run(), but with an explicit
1133  * rcu_read_lock() and migrate_disable() which are required
1134  * for the trampoline. The macro is split into
1135  * call __bpf_prog_enter
1136  * call prog->bpf_func
1137  * call __bpf_prog_exit
1138  *
1139  * __bpf_prog_enter returns:
1140  * 0 - skip execution of the bpf prog
1141  * 1 - execute bpf prog
1142  * [2..MAX_U64] - execute bpf prog and record execution time.
1143  *     This is start time.
1144  */
1145 static u64 notrace __bpf_prog_enter_recur(struct bpf_prog *prog, struct bpf_tramp_run_ctx *run_ctx)
1146 	__acquires(RCU)
1147 {
1148 	rcu_read_lock_dont_migrate();
1149 
1150 	run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
1151 
1152 	if (unlikely(!bpf_prog_get_recursion_context(prog))) {
1153 		bpf_prog_inc_misses_counter(prog);
1154 		if (prog->aux->recursion_detected)
1155 			prog->aux->recursion_detected(prog);
1156 		return 0;
1157 	}
1158 	return bpf_prog_start_time();
1159 }
1160 
1161 static void notrace __update_prog_stats(struct bpf_prog *prog, u64 start)
1162 {
1163 	struct bpf_prog_stats *stats;
1164 	unsigned long flags;
1165 	u64 duration;
1166 
1167 	/*
1168 	 * static_key could be enabled in __bpf_prog_enter* and disabled in
1169 	 * __bpf_prog_exit*. And vice versa. Check that 'start' is valid.
1170 	 */
1171 	if (start <= NO_START_TIME)
1172 		return;
1173 
1174 	duration = sched_clock() - start;
1175 	stats = this_cpu_ptr(prog->stats);
1176 	flags = u64_stats_update_begin_irqsave(&stats->syncp);
1177 	u64_stats_inc(&stats->cnt);
1178 	u64_stats_add(&stats->nsecs, duration);
1179 	u64_stats_update_end_irqrestore(&stats->syncp, flags);
1180 }
1181 
1182 static __always_inline void notrace update_prog_stats(struct bpf_prog *prog,
1183 						      u64 start)
1184 {
1185 	if (static_branch_unlikely(&bpf_stats_enabled_key))
1186 		__update_prog_stats(prog, start);
1187 }
1188 
1189 static void notrace __bpf_prog_exit_recur(struct bpf_prog *prog, u64 start,
1190 					  struct bpf_tramp_run_ctx *run_ctx)
1191 	__releases(RCU)
1192 {
1193 	bpf_reset_run_ctx(run_ctx->saved_run_ctx);
1194 
1195 	update_prog_stats(prog, start);
1196 	bpf_prog_put_recursion_context(prog);
1197 	rcu_read_unlock_migrate();
1198 }
1199 
1200 static u64 notrace __bpf_prog_enter_lsm_cgroup(struct bpf_prog *prog,
1201 					       struct bpf_tramp_run_ctx *run_ctx)
1202 	__acquires(RCU)
1203 {
1204 	/* Runtime stats are exported via actual BPF_LSM_CGROUP
1205 	 * programs, not the shims.
1206 	 */
1207 	rcu_read_lock_dont_migrate();
1208 
1209 	run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
1210 
1211 	return NO_START_TIME;
1212 }
1213 
1214 static void notrace __bpf_prog_exit_lsm_cgroup(struct bpf_prog *prog, u64 start,
1215 					       struct bpf_tramp_run_ctx *run_ctx)
1216 	__releases(RCU)
1217 {
1218 	bpf_reset_run_ctx(run_ctx->saved_run_ctx);
1219 
1220 	rcu_read_unlock_migrate();
1221 }
1222 
1223 u64 notrace __bpf_prog_enter_sleepable_recur(struct bpf_prog *prog,
1224 					     struct bpf_tramp_run_ctx *run_ctx)
1225 {
1226 	rcu_read_lock_trace();
1227 	migrate_disable();
1228 	might_fault();
1229 
1230 	run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
1231 
1232 	if (unlikely(!bpf_prog_get_recursion_context(prog))) {
1233 		bpf_prog_inc_misses_counter(prog);
1234 		if (prog->aux->recursion_detected)
1235 			prog->aux->recursion_detected(prog);
1236 		return 0;
1237 	}
1238 	return bpf_prog_start_time();
1239 }
1240 
1241 void notrace __bpf_prog_exit_sleepable_recur(struct bpf_prog *prog, u64 start,
1242 					     struct bpf_tramp_run_ctx *run_ctx)
1243 {
1244 	bpf_reset_run_ctx(run_ctx->saved_run_ctx);
1245 
1246 	update_prog_stats(prog, start);
1247 	bpf_prog_put_recursion_context(prog);
1248 	migrate_enable();
1249 	rcu_read_unlock_trace();
1250 }
1251 
1252 static u64 notrace __bpf_prog_enter_sleepable(struct bpf_prog *prog,
1253 					      struct bpf_tramp_run_ctx *run_ctx)
1254 {
1255 	rcu_read_lock_trace();
1256 	migrate_disable();
1257 	might_fault();
1258 
1259 	run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
1260 
1261 	return bpf_prog_start_time();
1262 }
1263 
1264 static void notrace __bpf_prog_exit_sleepable(struct bpf_prog *prog, u64 start,
1265 					      struct bpf_tramp_run_ctx *run_ctx)
1266 {
1267 	bpf_reset_run_ctx(run_ctx->saved_run_ctx);
1268 
1269 	update_prog_stats(prog, start);
1270 	migrate_enable();
1271 	rcu_read_unlock_trace();
1272 }
1273 
1274 static u64 notrace __bpf_prog_enter(struct bpf_prog *prog,
1275 				    struct bpf_tramp_run_ctx *run_ctx)
1276 	__acquires(RCU)
1277 {
1278 	rcu_read_lock_dont_migrate();
1279 
1280 	run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
1281 
1282 	return bpf_prog_start_time();
1283 }
1284 
1285 static void notrace __bpf_prog_exit(struct bpf_prog *prog, u64 start,
1286 				    struct bpf_tramp_run_ctx *run_ctx)
1287 	__releases(RCU)
1288 {
1289 	bpf_reset_run_ctx(run_ctx->saved_run_ctx);
1290 
1291 	update_prog_stats(prog, start);
1292 	rcu_read_unlock_migrate();
1293 }
1294 
1295 void notrace __bpf_tramp_enter(struct bpf_tramp_image *tr)
1296 {
1297 	percpu_ref_get(&tr->pcref);
1298 }
1299 
1300 void notrace __bpf_tramp_exit(struct bpf_tramp_image *tr)
1301 {
1302 	percpu_ref_put(&tr->pcref);
1303 }
1304 
1305 bpf_trampoline_enter_t bpf_trampoline_enter(const struct bpf_prog *prog)
1306 {
1307 	bool sleepable = prog->sleepable;
1308 
1309 	if (bpf_prog_check_recur(prog))
1310 		return sleepable ? __bpf_prog_enter_sleepable_recur :
1311 			__bpf_prog_enter_recur;
1312 
1313 	if (resolve_prog_type(prog) == BPF_PROG_TYPE_LSM &&
1314 	    prog->expected_attach_type == BPF_LSM_CGROUP)
1315 		return __bpf_prog_enter_lsm_cgroup;
1316 
1317 	return sleepable ? __bpf_prog_enter_sleepable : __bpf_prog_enter;
1318 }
1319 
1320 bpf_trampoline_exit_t bpf_trampoline_exit(const struct bpf_prog *prog)
1321 {
1322 	bool sleepable = prog->sleepable;
1323 
1324 	if (bpf_prog_check_recur(prog))
1325 		return sleepable ? __bpf_prog_exit_sleepable_recur :
1326 			__bpf_prog_exit_recur;
1327 
1328 	if (resolve_prog_type(prog) == BPF_PROG_TYPE_LSM &&
1329 	    prog->expected_attach_type == BPF_LSM_CGROUP)
1330 		return __bpf_prog_exit_lsm_cgroup;
1331 
1332 	return sleepable ? __bpf_prog_exit_sleepable : __bpf_prog_exit;
1333 }
1334 
1335 int __weak
1336 arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *image, void *image_end,
1337 			    const struct btf_func_model *m, u32 flags,
1338 			    struct bpf_tramp_links *tlinks,
1339 			    void *func_addr)
1340 {
1341 	return -ENOTSUPP;
1342 }
1343 
1344 void * __weak arch_alloc_bpf_trampoline(unsigned int size)
1345 {
1346 	void *image;
1347 
1348 	if (WARN_ON_ONCE(size > PAGE_SIZE))
1349 		return NULL;
1350 	image = bpf_jit_alloc_exec(PAGE_SIZE);
1351 	if (image)
1352 		set_vm_flush_reset_perms(image);
1353 	return image;
1354 }
1355 
1356 void __weak arch_free_bpf_trampoline(void *image, unsigned int size)
1357 {
1358 	WARN_ON_ONCE(size > PAGE_SIZE);
1359 	/* bpf_jit_free_exec doesn't need "size", but
1360 	 * bpf_prog_pack_free() needs it.
1361 	 */
1362 	bpf_jit_free_exec(image);
1363 }
1364 
1365 int __weak arch_protect_bpf_trampoline(void *image, unsigned int size)
1366 {
1367 	WARN_ON_ONCE(size > PAGE_SIZE);
1368 	return set_memory_rox((long)image, 1);
1369 }
1370 
1371 int __weak arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags,
1372 				    struct bpf_tramp_links *tlinks, void *func_addr)
1373 {
1374 	return -ENOTSUPP;
1375 }
1376 
1377 static int __init init_trampolines(void)
1378 {
1379 	int i;
1380 
1381 	for (i = 0; i < TRAMPOLINE_TABLE_SIZE; i++)
1382 		INIT_HLIST_HEAD(&trampoline_key_table[i]);
1383 	for (i = 0; i < TRAMPOLINE_TABLE_SIZE; i++)
1384 		INIT_HLIST_HEAD(&trampoline_ip_table[i]);
1385 	return 0;
1386 }
1387 late_initcall(init_trampolines);
1388