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