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