xref: /linux/kernel/bpf/trampoline.c (revision 5a8cd539ac19f7a68e68e1d25ef9ca2ff55b8500)
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 /*
34  * Keep 32 trampoline locks (5 bits) in the pool so trampoline_lock_all()
35  * stays below MAX_LOCK_DEPTH.  Each pool slot has a distinct lockdep
36  * class because trampoline_lock_all() takes all pool mutexes at once;
37  * otherwise lockdep would report recursive locking on same-class mutexes.
38  */
39 #define TRAMPOLINE_LOCKS_BITS 5
40 #define TRAMPOLINE_LOCKS_TABLE_SIZE (1 << TRAMPOLINE_LOCKS_BITS)
41 
42 static struct {
43 	struct mutex mutex;
44 	struct lock_class_key key;
45 } trampoline_locks[TRAMPOLINE_LOCKS_TABLE_SIZE];
46 
select_trampoline_lock(struct bpf_trampoline * tr)47 static struct mutex *select_trampoline_lock(struct bpf_trampoline *tr)
48 {
49 	return &trampoline_locks[hash_ptr(tr, TRAMPOLINE_LOCKS_BITS)].mutex;
50 }
51 
trampoline_lock(struct bpf_trampoline * tr)52 static void trampoline_lock(struct bpf_trampoline *tr)
53 {
54 	mutex_lock(select_trampoline_lock(tr));
55 }
56 
trampoline_unlock(struct bpf_trampoline * tr)57 static void trampoline_unlock(struct bpf_trampoline *tr)
58 {
59 	mutex_unlock(select_trampoline_lock(tr));
60 }
61 
62 struct bpf_trampoline_ops {
63 	int (*register_fentry)(struct bpf_trampoline *tr, struct bpf_tramp_image *im, void *data);
64 	int (*unregister_fentry)(struct bpf_trampoline *tr, u32 orig_flags, void *data);
65 	int (*modify_fentry)(struct bpf_trampoline *tr, u32 orig_flags, struct bpf_tramp_image *im,
66 			     bool lock_direct_mutex, void *data);
67 };
68 
69 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
70 static int bpf_trampoline_update(struct bpf_trampoline *tr, bool lock_direct_mutex,
71 				 const struct bpf_trampoline_ops *ops, void *data);
72 static const struct bpf_trampoline_ops trampoline_ops;
73 
74 #ifdef CONFIG_HAVE_SINGLE_FTRACE_DIRECT_OPS
direct_ops_ip_lookup(struct ftrace_ops * ops,unsigned long ip)75 static struct bpf_trampoline *direct_ops_ip_lookup(struct ftrace_ops *ops, unsigned long ip)
76 {
77 	struct hlist_head *head_ip;
78 	struct bpf_trampoline *tr;
79 
80 	mutex_lock(&trampoline_mutex);
81 	head_ip = &trampoline_ip_table[hash_64(ip, TRAMPOLINE_HASH_BITS)];
82 	hlist_for_each_entry(tr, head_ip, hlist_ip) {
83 		if (tr->ip == ip)
84 			goto out;
85 	}
86 	tr = NULL;
87 out:
88 	mutex_unlock(&trampoline_mutex);
89 	return tr;
90 }
91 #else
direct_ops_ip_lookup(struct ftrace_ops * ops,unsigned long ip)92 static struct bpf_trampoline *direct_ops_ip_lookup(struct ftrace_ops *ops, unsigned long ip)
93 {
94 	return ops->private;
95 }
96 #endif /* CONFIG_HAVE_SINGLE_FTRACE_DIRECT_OPS */
97 
bpf_tramp_ftrace_ops_func(struct ftrace_ops * ops,unsigned long ip,enum ftrace_ops_cmd cmd)98 static int bpf_tramp_ftrace_ops_func(struct ftrace_ops *ops, unsigned long ip,
99 				     enum ftrace_ops_cmd cmd)
100 {
101 	struct bpf_trampoline *tr;
102 	int ret = 0;
103 
104 	tr = direct_ops_ip_lookup(ops, ip);
105 	if (!tr)
106 		return -EINVAL;
107 
108 	if (cmd == FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_SELF) {
109 		/* This is called inside register_ftrace_direct_multi(), so
110 		 * trampoline's mutex is already locked.
111 		 */
112 		lockdep_assert_held_once(select_trampoline_lock(tr));
113 
114 		/* Instead of updating the trampoline here, we propagate
115 		 * -EAGAIN to register_ftrace_direct(). Then we can
116 		 * retry register_ftrace_direct() after updating the
117 		 * trampoline.
118 		 */
119 		if ((tr->flags & BPF_TRAMP_F_CALL_ORIG) &&
120 		    !(tr->flags & BPF_TRAMP_F_ORIG_STACK)) {
121 			if (WARN_ON_ONCE(tr->flags & BPF_TRAMP_F_SHARE_IPMODIFY))
122 				return -EBUSY;
123 
124 			tr->flags |= BPF_TRAMP_F_SHARE_IPMODIFY;
125 			return -EAGAIN;
126 		}
127 
128 		return 0;
129 	}
130 
131 	/* The normal locking order is
132 	 *    select_trampoline_lock(tr) => direct_mutex (ftrace.c) => ftrace_lock (ftrace.c)
133 	 *
134 	 * The following two commands are called from
135 	 *
136 	 *   prepare_direct_functions_for_ipmodify
137 	 *   cleanup_direct_functions_after_ipmodify
138 	 *
139 	 * In both cases, direct_mutex is already locked. Use
140 	 * mutex_trylock(select_trampoline_lock(tr)) to avoid deadlock in race condition
141 	 * (something else holds the same pool lock).
142 	 */
143 	if (!mutex_trylock(select_trampoline_lock(tr))) {
144 		/* sleep 1 ms to make sure whatever holding select_trampoline_lock(tr)
145 		 * makes some progress.
146 		 */
147 		msleep(1);
148 		return -EAGAIN;
149 	}
150 
151 	switch (cmd) {
152 	case FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER:
153 		tr->flags |= BPF_TRAMP_F_SHARE_IPMODIFY;
154 
155 		if ((tr->flags & BPF_TRAMP_F_CALL_ORIG) &&
156 		    !(tr->flags & BPF_TRAMP_F_ORIG_STACK))
157 			ret = bpf_trampoline_update(tr, false /* lock_direct_mutex */,
158 						    &trampoline_ops, NULL);
159 		break;
160 	case FTRACE_OPS_CMD_DISABLE_SHARE_IPMODIFY_PEER:
161 		tr->flags &= ~BPF_TRAMP_F_SHARE_IPMODIFY;
162 
163 		if (tr->flags & BPF_TRAMP_F_ORIG_STACK)
164 			ret = bpf_trampoline_update(tr, false /* lock_direct_mutex */,
165 						    &trampoline_ops, NULL);
166 		break;
167 	default:
168 		ret = -EINVAL;
169 		break;
170 	}
171 
172 	trampoline_unlock(tr);
173 	return ret;
174 }
175 #endif
176 
bpf_prog_has_trampoline(const struct bpf_prog * prog)177 bool bpf_prog_has_trampoline(const struct bpf_prog *prog)
178 {
179 	enum bpf_attach_type eatype = prog->expected_attach_type;
180 	enum bpf_prog_type ptype = prog->type;
181 
182 	switch (ptype) {
183 	case BPF_PROG_TYPE_TRACING:
184 		if (eatype == BPF_TRACE_FENTRY || eatype == BPF_TRACE_FEXIT ||
185 		    eatype == BPF_MODIFY_RETURN || eatype == BPF_TRACE_FSESSION ||
186 		    eatype == BPF_TRACE_FENTRY_MULTI || eatype == BPF_TRACE_FEXIT_MULTI ||
187 		    eatype == BPF_TRACE_FSESSION_MULTI)
188 			return true;
189 		return false;
190 	case BPF_PROG_TYPE_LSM:
191 		return eatype == BPF_LSM_MAC;
192 	default:
193 		return false;
194 	}
195 }
196 
bpf_image_ksym_init(void * data,unsigned int size,struct bpf_ksym * ksym)197 void bpf_image_ksym_init(void *data, unsigned int size, struct bpf_ksym *ksym)
198 {
199 	ksym->start = (unsigned long) data;
200 	ksym->end = ksym->start + size;
201 }
202 
bpf_image_ksym_add(struct bpf_ksym * ksym)203 void bpf_image_ksym_add(struct bpf_ksym *ksym)
204 {
205 	bpf_ksym_add(ksym);
206 	perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, ksym->start,
207 			   PAGE_SIZE, false, ksym->name);
208 }
209 
bpf_image_ksym_del(struct bpf_ksym * ksym)210 void bpf_image_ksym_del(struct bpf_ksym *ksym)
211 {
212 	bpf_ksym_del(ksym);
213 	perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, ksym->start,
214 			   PAGE_SIZE, true, ksym->name);
215 }
216 
217 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
218 #ifdef CONFIG_HAVE_SINGLE_FTRACE_DIRECT_OPS
219 /*
220  * We have only single direct_ops which contains all the direct call
221  * sites and is the only global ftrace_ops for all trampolines.
222  *
223  * We use 'update_ftrace_direct_*' api for attachment.
224  */
225 struct ftrace_ops direct_ops = {
226 	.ops_func = bpf_tramp_ftrace_ops_func,
227 };
228 
direct_ops_alloc(struct bpf_trampoline * tr)229 static int direct_ops_alloc(struct bpf_trampoline *tr)
230 {
231 	tr->fops = &direct_ops;
232 	return 0;
233 }
234 
direct_ops_free(struct bpf_trampoline * tr)235 static void direct_ops_free(struct bpf_trampoline *tr) { }
236 
hash_from_ip(struct bpf_trampoline * tr,void * ptr)237 static struct ftrace_hash *hash_from_ip(struct bpf_trampoline *tr, void *ptr)
238 {
239 	unsigned long ip, addr = (unsigned long) ptr;
240 	struct ftrace_hash *hash;
241 
242 	ip = ftrace_location(tr->ip);
243 	if (!ip)
244 		return NULL;
245 	hash = alloc_ftrace_hash(FTRACE_HASH_DEFAULT_BITS);
246 	if (!hash)
247 		return NULL;
248 	if (bpf_trampoline_use_jmp(tr->flags))
249 		addr = ftrace_jmp_set(addr);
250 	if (!add_ftrace_hash_entry_direct(hash, ip, addr)) {
251 		free_ftrace_hash(hash);
252 		return NULL;
253 	}
254 	return hash;
255 }
256 
direct_ops_add(struct bpf_trampoline * tr,void * addr)257 static int direct_ops_add(struct bpf_trampoline *tr, void *addr)
258 {
259 	struct ftrace_hash *hash = hash_from_ip(tr, addr);
260 	int err;
261 
262 	if (!hash)
263 		return -ENOMEM;
264 	err = update_ftrace_direct_add(tr->fops, hash);
265 	free_ftrace_hash(hash);
266 	return err;
267 }
268 
direct_ops_del(struct bpf_trampoline * tr,void * addr)269 static int direct_ops_del(struct bpf_trampoline *tr, void *addr)
270 {
271 	struct ftrace_hash *hash = hash_from_ip(tr, addr);
272 	int err;
273 
274 	if (!hash)
275 		return -ENOMEM;
276 	err = update_ftrace_direct_del(tr->fops, hash);
277 	free_ftrace_hash(hash);
278 	return err;
279 }
280 
direct_ops_mod(struct bpf_trampoline * tr,void * addr,bool lock_direct_mutex)281 static int direct_ops_mod(struct bpf_trampoline *tr, void *addr, bool lock_direct_mutex)
282 {
283 	struct ftrace_hash *hash = hash_from_ip(tr, addr);
284 	int err;
285 
286 	if (!hash)
287 		return -ENOMEM;
288 	err = update_ftrace_direct_mod(tr->fops, hash, lock_direct_mutex);
289 	free_ftrace_hash(hash);
290 	return err;
291 }
292 #else
293 /*
294  * We allocate ftrace_ops object for each trampoline and it contains
295  * call site specific for that trampoline.
296  *
297  * We use *_ftrace_direct api for attachment.
298  */
direct_ops_alloc(struct bpf_trampoline * tr)299 static int direct_ops_alloc(struct bpf_trampoline *tr)
300 {
301 	tr->fops = kzalloc_obj(struct ftrace_ops);
302 	if (!tr->fops)
303 		return -ENOMEM;
304 	tr->fops->private = tr;
305 	tr->fops->ops_func = bpf_tramp_ftrace_ops_func;
306 	return 0;
307 }
308 
direct_ops_free(struct bpf_trampoline * tr)309 static void direct_ops_free(struct bpf_trampoline *tr)
310 {
311 	if (!tr->fops)
312 		return;
313 	ftrace_free_filter(tr->fops);
314 	kfree(tr->fops);
315 }
316 
direct_ops_add(struct bpf_trampoline * tr,void * ptr)317 static int direct_ops_add(struct bpf_trampoline *tr, void *ptr)
318 {
319 	unsigned long addr = (unsigned long) ptr;
320 	struct ftrace_ops *ops = tr->fops;
321 	int ret;
322 
323 	if (bpf_trampoline_use_jmp(tr->flags))
324 		addr = ftrace_jmp_set(addr);
325 
326 	ret = ftrace_set_filter_ip(ops, tr->ip, 0, 1);
327 	if (ret)
328 		return ret;
329 	return register_ftrace_direct(ops, addr);
330 }
331 
direct_ops_del(struct bpf_trampoline * tr,void * addr)332 static int direct_ops_del(struct bpf_trampoline *tr, void *addr)
333 {
334 	return unregister_ftrace_direct(tr->fops, (long)addr, false);
335 }
336 
direct_ops_mod(struct bpf_trampoline * tr,void * ptr,bool lock_direct_mutex)337 static int direct_ops_mod(struct bpf_trampoline *tr, void *ptr, bool lock_direct_mutex)
338 {
339 	unsigned long addr = (unsigned long) ptr;
340 	struct ftrace_ops *ops = tr->fops;
341 
342 	if (bpf_trampoline_use_jmp(tr->flags))
343 		addr = ftrace_jmp_set(addr);
344 	if (lock_direct_mutex)
345 		return modify_ftrace_direct(ops, addr);
346 	return modify_ftrace_direct_nolock(ops, addr);
347 }
348 #endif /* CONFIG_HAVE_SINGLE_FTRACE_DIRECT_OPS */
349 #else
direct_ops_free(struct bpf_trampoline * tr)350 static void direct_ops_free(struct bpf_trampoline *tr) { }
351 
direct_ops_alloc(struct bpf_trampoline * tr)352 static int direct_ops_alloc(struct bpf_trampoline *tr)
353 {
354 	return 0;
355 }
356 
direct_ops_add(struct bpf_trampoline * tr,void * addr)357 static int direct_ops_add(struct bpf_trampoline *tr, void *addr)
358 {
359 	return -ENODEV;
360 }
361 
direct_ops_del(struct bpf_trampoline * tr,void * addr)362 static int direct_ops_del(struct bpf_trampoline *tr, void *addr)
363 {
364 	return -ENODEV;
365 }
366 
direct_ops_mod(struct bpf_trampoline * tr,void * ptr,bool lock_direct_mutex)367 static int direct_ops_mod(struct bpf_trampoline *tr, void *ptr, bool lock_direct_mutex)
368 {
369 	return -ENODEV;
370 }
371 #endif /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS */
372 
bpf_trampoline_lookup(u64 key,unsigned long ip)373 static struct bpf_trampoline *bpf_trampoline_lookup(u64 key, unsigned long ip)
374 {
375 	struct bpf_trampoline *tr;
376 	struct hlist_head *head;
377 	int i;
378 
379 	mutex_lock(&trampoline_mutex);
380 	head = &trampoline_key_table[hash_64(key, TRAMPOLINE_HASH_BITS)];
381 	hlist_for_each_entry(tr, head, hlist_key) {
382 		if (tr->key == key) {
383 			refcount_inc(&tr->refcnt);
384 			goto out;
385 		}
386 	}
387 	tr = kzalloc_obj(*tr);
388 	if (!tr)
389 		goto out;
390 	if (direct_ops_alloc(tr)) {
391 		kfree(tr);
392 		tr = NULL;
393 		goto out;
394 	}
395 
396 	tr->key = key;
397 	tr->ip = ftrace_location(ip);
398 	INIT_HLIST_NODE(&tr->hlist_key);
399 	INIT_HLIST_NODE(&tr->hlist_ip);
400 	hlist_add_head(&tr->hlist_key, head);
401 	head = &trampoline_ip_table[hash_64(tr->ip, TRAMPOLINE_HASH_BITS)];
402 	hlist_add_head(&tr->hlist_ip, head);
403 	refcount_set(&tr->refcnt, 1);
404 	for (i = 0; i < BPF_TRAMP_MAX; i++)
405 		INIT_HLIST_HEAD(&tr->progs_hlist[i]);
406 out:
407 	mutex_unlock(&trampoline_mutex);
408 	return tr;
409 }
410 
bpf_trampoline_update_fentry(struct bpf_trampoline * tr,u32 orig_flags,void * old_addr,void * new_addr)411 static int bpf_trampoline_update_fentry(struct bpf_trampoline *tr, u32 orig_flags,
412 					void *old_addr, void *new_addr)
413 {
414 	enum bpf_text_poke_type new_t = BPF_MOD_CALL, old_t = BPF_MOD_CALL;
415 	void *ip = tr->func.addr;
416 
417 	if (!new_addr)
418 		new_t = BPF_MOD_NOP;
419 	else if (bpf_trampoline_use_jmp(tr->flags))
420 		new_t = BPF_MOD_JUMP;
421 
422 	if (!old_addr)
423 		old_t = BPF_MOD_NOP;
424 	else if (bpf_trampoline_use_jmp(orig_flags))
425 		old_t = BPF_MOD_JUMP;
426 
427 	return bpf_arch_text_poke(ip, old_t, new_t, old_addr, new_addr);
428 }
429 
430 static void bpf_tramp_image_put(struct bpf_tramp_image *im);
431 
unregister_fentry(struct bpf_trampoline * tr,u32 orig_flags,void * data __maybe_unused)432 static int unregister_fentry(struct bpf_trampoline *tr, u32 orig_flags, void *data __maybe_unused)
433 {
434 	void *old_addr = tr->cur_image->image;
435 	int ret;
436 
437 	if (tr->func.ftrace_managed)
438 		ret = direct_ops_del(tr, old_addr);
439 	else
440 		ret = bpf_trampoline_update_fentry(tr, orig_flags, old_addr, NULL);
441 
442 	if (ret)
443 		return ret;
444 
445 	bpf_tramp_image_put(tr->cur_image);
446 	tr->cur_image = NULL;
447 	return 0;
448 }
449 
modify_fentry(struct bpf_trampoline * tr,u32 orig_flags,struct bpf_tramp_image * im,bool lock_direct_mutex,void * data __maybe_unused)450 static int modify_fentry(struct bpf_trampoline *tr, u32 orig_flags, struct bpf_tramp_image *im,
451 			 bool lock_direct_mutex, void *data __maybe_unused)
452 {
453 	void *old_addr = tr->cur_image->image;
454 	void *new_addr = im->image;
455 	int ret;
456 
457 	if (tr->func.ftrace_managed) {
458 		ret = direct_ops_mod(tr, new_addr, lock_direct_mutex);
459 	} else {
460 		ret = bpf_trampoline_update_fentry(tr, orig_flags, old_addr,
461 						   new_addr);
462 	}
463 
464 	if (ret)
465 		return ret;
466 
467 	bpf_tramp_image_put(tr->cur_image);
468 	tr->cur_image = im;
469 	return 0;
470 }
471 
472 /* first time registering */
register_fentry(struct bpf_trampoline * tr,struct bpf_tramp_image * im,void * data __maybe_unused)473 static int register_fentry(struct bpf_trampoline *tr, struct bpf_tramp_image *im,
474 			   void *data __maybe_unused)
475 {
476 	void *new_addr = im->image;
477 	void *ip = tr->func.addr;
478 	unsigned long faddr;
479 	int ret;
480 
481 	faddr = ftrace_location((unsigned long)ip);
482 	if (faddr) {
483 		if (!tr->fops)
484 			return -ENOTSUPP;
485 		tr->func.ftrace_managed = true;
486 	}
487 
488 	if (tr->func.ftrace_managed) {
489 		ret = direct_ops_add(tr, new_addr);
490 	} else {
491 		ret = bpf_trampoline_update_fentry(tr, 0, NULL, new_addr);
492 	}
493 
494 	if (ret)
495 		return ret;
496 
497 	tr->cur_image = im;
498 	return 0;
499 }
500 
501 static const struct bpf_trampoline_ops trampoline_ops = {
502 	.register_fentry   = register_fentry,
503 	.unregister_fentry = unregister_fentry,
504 	.modify_fentry     = modify_fentry,
505 };
506 
507 static struct bpf_tramp_nodes *
bpf_trampoline_get_progs(const struct bpf_trampoline * tr,int * total,bool * ip_arg)508 bpf_trampoline_get_progs(const struct bpf_trampoline *tr, int *total, bool *ip_arg)
509 {
510 	struct bpf_tramp_node *node, **nodes;
511 	struct bpf_tramp_nodes *tnodes;
512 	int kind;
513 
514 	*total = 0;
515 	tnodes = kzalloc_objs(*tnodes, BPF_TRAMP_MAX);
516 	if (!tnodes)
517 		return ERR_PTR(-ENOMEM);
518 
519 	for (kind = 0; kind < BPF_TRAMP_MAX; kind++) {
520 		tnodes[kind].nr_nodes = tr->progs_cnt[kind];
521 		*total += tr->progs_cnt[kind];
522 		nodes = tnodes[kind].nodes;
523 
524 		hlist_for_each_entry(node, &tr->progs_hlist[kind], tramp_hlist) {
525 			*ip_arg |= node->link->prog->call_get_func_ip;
526 			*nodes++ = node;
527 		}
528 	}
529 	return tnodes;
530 }
531 
532 /*
533  * The arena base against which save_args() converts the arguments marked
534  * with BTF_FMODEL_ARENA_ARG. Only the struct_ops indirect trampoline
535  * converts: it dispatches to a single prog whose arena is known at
536  * generation time. Return 0 when there is nothing to convert.
537  */
bpf_tramp_arena_base(const struct btf_func_model * m,struct bpf_tramp_nodes * tnodes,u32 flags)538 u64 bpf_tramp_arena_base(const struct btf_func_model *m,
539 			 struct bpf_tramp_nodes *tnodes, u32 flags)
540 {
541 	const struct bpf_prog *prog;
542 	int i;
543 
544 	if (!(flags & BPF_TRAMP_F_INDIRECT) ||
545 	    tnodes[BPF_TRAMP_FENTRY].nr_nodes != 1)
546 		return 0;
547 
548 	for (i = 0; i < m->nr_args; i++)
549 		if (m->arg_flags[i] & BTF_FMODEL_ARENA_ARG)
550 			break;
551 	if (i == m->nr_args)
552 		return 0;
553 
554 	/* Verification rejects an arena argument without an arena. */
555 	prog = tnodes[BPF_TRAMP_FENTRY].nodes[0]->link->prog;
556 	if (WARN_ON_ONCE(!prog->aux->arena))
557 		return 0;
558 
559 	return bpf_arena_get_kern_vm_start(prog->aux->arena);
560 }
561 
bpf_tramp_image_free(struct bpf_tramp_image * im)562 static void bpf_tramp_image_free(struct bpf_tramp_image *im)
563 {
564 	bpf_image_ksym_del(&im->ksym);
565 	arch_free_bpf_trampoline(im->image, im->size);
566 	bpf_jit_uncharge_modmem(im->size);
567 	percpu_ref_exit(&im->pcref);
568 	kfree_rcu(im, rcu);
569 }
570 
__bpf_tramp_image_put_deferred(struct work_struct * work)571 static void __bpf_tramp_image_put_deferred(struct work_struct *work)
572 {
573 	struct bpf_tramp_image *im;
574 
575 	im = container_of(work, struct bpf_tramp_image, work);
576 	bpf_tramp_image_free(im);
577 }
578 
579 /* callback, fexit step 3 or fentry step 2 */
__bpf_tramp_image_put_rcu(struct rcu_head * rcu)580 static void __bpf_tramp_image_put_rcu(struct rcu_head *rcu)
581 {
582 	struct bpf_tramp_image *im;
583 
584 	im = container_of(rcu, struct bpf_tramp_image, rcu);
585 	INIT_WORK(&im->work, __bpf_tramp_image_put_deferred);
586 	schedule_work(&im->work);
587 }
588 
589 /* callback, fexit step 2. Called after percpu_ref_kill confirms. */
__bpf_tramp_image_release(struct percpu_ref * pcref)590 static void __bpf_tramp_image_release(struct percpu_ref *pcref)
591 {
592 	struct bpf_tramp_image *im;
593 
594 	im = container_of(pcref, struct bpf_tramp_image, pcref);
595 	call_rcu_tasks(&im->rcu, __bpf_tramp_image_put_rcu);
596 }
597 
598 /* callback, fexit or fentry step 1 */
__bpf_tramp_image_put_rcu_tasks(struct rcu_head * rcu)599 static void __bpf_tramp_image_put_rcu_tasks(struct rcu_head *rcu)
600 {
601 	struct bpf_tramp_image *im;
602 
603 	im = container_of(rcu, struct bpf_tramp_image, rcu);
604 	if (im->ip_after_call)
605 		/* the case of fmod_ret/fexit trampoline and CONFIG_PREEMPTION=y */
606 		percpu_ref_kill(&im->pcref);
607 	else
608 		/* the case of fentry trampoline */
609 		call_rcu_tasks(&im->rcu, __bpf_tramp_image_put_rcu);
610 }
611 
bpf_tramp_image_put(struct bpf_tramp_image * im)612 static void bpf_tramp_image_put(struct bpf_tramp_image *im)
613 {
614 	/* The trampoline image that calls original function is using:
615 	 * rcu_read_lock_trace to protect sleepable bpf progs
616 	 * rcu_read_lock to protect normal bpf progs
617 	 * percpu_ref to protect trampoline itself
618 	 * rcu tasks to protect trampoline asm not covered by percpu_ref
619 	 * (which are few asm insns before __bpf_tramp_enter and
620 	 *  after __bpf_tramp_exit)
621 	 *
622 	 * The trampoline is unreachable before bpf_tramp_image_put().
623 	 *
624 	 * First, patch the trampoline to avoid calling into fexit progs.
625 	 * The progs will be freed even if the original function is still
626 	 * executing or sleeping.
627 	 * In case of CONFIG_PREEMPT=y use call_rcu_tasks() to wait on
628 	 * first few asm instructions to execute and call into
629 	 * __bpf_tramp_enter->percpu_ref_get.
630 	 * Then use percpu_ref_kill to wait for the trampoline and the original
631 	 * function to finish.
632 	 * Then use call_rcu_tasks() to make sure few asm insns in
633 	 * the trampoline epilogue are done as well.
634 	 *
635 	 * In !PREEMPT case the task that got interrupted in the first asm
636 	 * insns won't go through an RCU quiescent state which the
637 	 * percpu_ref_kill will be waiting for. Hence the first
638 	 * call_rcu_tasks() is not necessary.
639 	 */
640 	if (im->ip_after_call) {
641 		int err = bpf_arch_text_poke(im->ip_after_call, BPF_MOD_NOP,
642 					     BPF_MOD_JUMP, NULL,
643 					     im->ip_epilogue);
644 		WARN_ON(err);
645 		if (IS_ENABLED(CONFIG_TASKS_RCU))
646 			call_rcu_tasks(&im->rcu, __bpf_tramp_image_put_rcu_tasks);
647 		else
648 			percpu_ref_kill(&im->pcref);
649 		return;
650 	}
651 
652 	/* The trampoline without fexit and fmod_ret progs doesn't call original
653 	 * function and doesn't use percpu_ref.
654 	 * Use call_rcu_tasks_trace() to wait for sleepable progs to finish.
655 	 * Then use call_rcu_tasks() to wait for the rest of trampoline asm
656 	 * and normal progs.
657 	 */
658 	call_rcu_tasks_trace(&im->rcu, __bpf_tramp_image_put_rcu_tasks);
659 }
660 
bpf_tramp_image_alloc(u64 key,int size)661 static struct bpf_tramp_image *bpf_tramp_image_alloc(u64 key, int size)
662 {
663 	struct bpf_tramp_image *im;
664 	struct bpf_ksym *ksym;
665 	void *image;
666 	int err = -ENOMEM;
667 
668 	im = kzalloc_obj(*im);
669 	if (!im)
670 		goto out;
671 
672 	err = bpf_jit_charge_modmem(size);
673 	if (err)
674 		goto out_free_im;
675 	im->size = size;
676 
677 	err = -ENOMEM;
678 	im->image = image = arch_alloc_bpf_trampoline(size);
679 	if (!image)
680 		goto out_uncharge;
681 
682 	err = percpu_ref_init(&im->pcref, __bpf_tramp_image_release, 0, GFP_KERNEL);
683 	if (err)
684 		goto out_free_image;
685 
686 	ksym = &im->ksym;
687 	INIT_LIST_HEAD_RCU(&ksym->lnode);
688 	snprintf(ksym->name, KSYM_NAME_LEN, "bpf_trampoline_%llu", key);
689 	bpf_image_ksym_init(image, size, ksym);
690 	bpf_image_ksym_add(ksym);
691 	return im;
692 
693 out_free_image:
694 	arch_free_bpf_trampoline(im->image, im->size);
695 out_uncharge:
696 	bpf_jit_uncharge_modmem(size);
697 out_free_im:
698 	kfree(im);
699 out:
700 	return ERR_PTR(err);
701 }
702 
bpf_trampoline_set_flags(struct bpf_trampoline * tr,u32 flags)703 void bpf_trampoline_set_flags(struct bpf_trampoline *tr, u32 flags)
704 {
705 	trampoline_lock(tr);
706 	tr->flags |= flags;
707 	trampoline_unlock(tr);
708 }
709 
bpf_trampoline_update(struct bpf_trampoline * tr,bool lock_direct_mutex,const struct bpf_trampoline_ops * ops,void * data)710 static int bpf_trampoline_update(struct bpf_trampoline *tr, bool lock_direct_mutex,
711 				 const struct bpf_trampoline_ops *ops, void *data)
712 {
713 	struct bpf_tramp_image *im;
714 	struct bpf_tramp_nodes *tnodes;
715 	u32 orig_flags = tr->flags;
716 	bool ip_arg = false;
717 	int err, total, size;
718 
719 	tnodes = bpf_trampoline_get_progs(tr, &total, &ip_arg);
720 	if (IS_ERR(tnodes))
721 		return PTR_ERR(tnodes);
722 
723 	if (total == 0) {
724 		err = ops->unregister_fentry(tr, orig_flags, data);
725 		goto out;
726 	}
727 
728 	/* clear all bits except SHARE_IPMODIFY and TAIL_CALL_CTX */
729 	tr->flags &= (BPF_TRAMP_F_SHARE_IPMODIFY | BPF_TRAMP_F_TAIL_CALL_CTX);
730 
731 	if (tnodes[BPF_TRAMP_FEXIT].nr_nodes ||
732 	    tnodes[BPF_TRAMP_MODIFY_RETURN].nr_nodes) {
733 		/* NOTE: BPF_TRAMP_F_RESTORE_REGS and BPF_TRAMP_F_SKIP_FRAME
734 		 * should not be set together.
735 		 */
736 		tr->flags |= BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_SKIP_FRAME;
737 	} else {
738 		tr->flags |= BPF_TRAMP_F_RESTORE_REGS;
739 	}
740 
741 	if (ip_arg)
742 		tr->flags |= BPF_TRAMP_F_IP_ARG;
743 
744 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
745 again:
746 	if (tr->flags & BPF_TRAMP_F_CALL_ORIG) {
747 		if (tr->flags & BPF_TRAMP_F_SHARE_IPMODIFY) {
748 			/* The BPF_TRAMP_F_SKIP_FRAME can be cleared in the
749 			 * first try, reset it in the second try.
750 			 */
751 			tr->flags |= BPF_TRAMP_F_ORIG_STACK | BPF_TRAMP_F_SKIP_FRAME;
752 		} else if (IS_ENABLED(CONFIG_DYNAMIC_FTRACE_WITH_JMP)) {
753 			/* Use "jmp" instead of "call" for the trampoline
754 			 * in the origin call case, and we don't need to
755 			 * skip the frame.
756 			 */
757 			tr->flags &= ~BPF_TRAMP_F_SKIP_FRAME;
758 		}
759 	}
760 #endif
761 
762 	size = arch_bpf_trampoline_size(&tr->func.model, tr->flags,
763 					tnodes, tr->func.addr);
764 	if (size < 0) {
765 		err = size;
766 		goto out;
767 	}
768 
769 	if (size > PAGE_SIZE) {
770 		err = -E2BIG;
771 		goto out;
772 	}
773 
774 	im = bpf_tramp_image_alloc(tr->key, size);
775 	if (IS_ERR(im)) {
776 		err = PTR_ERR(im);
777 		goto out;
778 	}
779 
780 	err = arch_prepare_bpf_trampoline(im, im->image, im->image + size,
781 					  &tr->func.model, tr->flags, tnodes,
782 					  tr->func.addr);
783 	if (err < 0)
784 		goto out_free;
785 
786 	err = arch_protect_bpf_trampoline(im->image, im->size);
787 	if (err)
788 		goto out_free;
789 
790 	if (tr->cur_image)
791 		/* progs already running at this address */
792 		err = ops->modify_fentry(tr, orig_flags, im, lock_direct_mutex, data);
793 	else
794 		/* first time registering */
795 		err = ops->register_fentry(tr, im, data);
796 
797 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
798 	if (err == -EAGAIN) {
799 		/* -EAGAIN from bpf_tramp_ftrace_ops_func. Now
800 		 * BPF_TRAMP_F_SHARE_IPMODIFY is set, we can generate the
801 		 * trampoline again, and retry register.
802 		 */
803 		bpf_tramp_image_free(im);
804 		goto again;
805 	}
806 #endif
807 
808 out_free:
809 	if (err)
810 		bpf_tramp_image_free(im);
811 out:
812 	/* If any error happens, restore previous flags */
813 	if (err)
814 		tr->flags = orig_flags;
815 	kfree(tnodes);
816 	return err;
817 }
818 
bpf_attach_type_to_tramp(struct bpf_prog * prog)819 static enum bpf_tramp_prog_type bpf_attach_type_to_tramp(struct bpf_prog *prog)
820 {
821 	switch (prog->expected_attach_type) {
822 	case BPF_TRACE_FENTRY:
823 	case BPF_TRACE_FENTRY_MULTI:
824 		return BPF_TRAMP_FENTRY;
825 	case BPF_MODIFY_RETURN:
826 		return BPF_TRAMP_MODIFY_RETURN;
827 	case BPF_TRACE_FEXIT:
828 	case BPF_TRACE_FEXIT_MULTI:
829 		return BPF_TRAMP_FEXIT;
830 	case BPF_TRACE_FSESSION:
831 	case BPF_TRACE_FSESSION_MULTI:
832 		return BPF_TRAMP_FSESSION;
833 	case BPF_LSM_MAC:
834 		if (!prog->aux->attach_func_proto->type)
835 			/* The function returns void, we cannot modify its
836 			 * return value.
837 			 */
838 			return BPF_TRAMP_FEXIT;
839 		else
840 			return BPF_TRAMP_MODIFY_RETURN;
841 	default:
842 		return BPF_TRAMP_REPLACE;
843 	}
844 }
845 
bpf_freplace_check_tgt_prog(struct bpf_prog * tgt_prog)846 static int bpf_freplace_check_tgt_prog(struct bpf_prog *tgt_prog)
847 {
848 	struct bpf_prog_aux *aux = tgt_prog->aux;
849 
850 	guard(mutex)(&aux->ext_mutex);
851 	if (aux->prog_array_member_cnt)
852 		/* Program extensions can not extend target prog when the target
853 		 * prog has been updated to any prog_array map as tail callee.
854 		 * It's to prevent a potential infinite loop like:
855 		 * tgt prog entry -> tgt prog subprog -> freplace prog entry
856 		 * --tailcall-> tgt prog entry.
857 		 */
858 		return -EBUSY;
859 
860 	aux->is_extended = true;
861 	return 0;
862 }
863 
fsession_exit(struct bpf_tramp_node * node)864 static struct bpf_tramp_node *fsession_exit(struct bpf_tramp_node *node)
865 {
866 	if (node->link->type == BPF_LINK_TYPE_TRACING) {
867 		struct bpf_tracing_link *link;
868 
869 		link = container_of(node->link, struct bpf_tracing_link, link.link);
870 		return &link->fexit;
871 	} else if (node->link->type == BPF_LINK_TYPE_TRACING_MULTI) {
872 		struct bpf_tracing_multi_link *link;
873 		struct bpf_tracing_multi_node *mnode;
874 
875 		link = container_of(node->link, struct bpf_tracing_multi_link, link);
876 		mnode = container_of(node, struct bpf_tracing_multi_node, node);
877 		return &link->fexits[mnode - link->nodes];
878 	}
879 	return NULL;
880 }
881 
bpf_trampoline_add_prog(struct bpf_trampoline * tr,struct bpf_tramp_node * node,int cnt)882 static int bpf_trampoline_add_prog(struct bpf_trampoline *tr,
883 				   struct bpf_tramp_node *node,
884 				   int cnt)
885 {
886 	enum bpf_tramp_prog_type kind;
887 	struct bpf_tramp_node *node_existing, *fexit;
888 	struct hlist_head *prog_list;
889 
890 	kind = bpf_attach_type_to_tramp(node->link->prog);
891 	if (kind == BPF_TRAMP_FSESSION) {
892 		prog_list = &tr->progs_hlist[BPF_TRAMP_FENTRY];
893 		cnt++;
894 	} else {
895 		prog_list = &tr->progs_hlist[kind];
896 	}
897 	if (cnt >= BPF_MAX_TRAMP_LINKS)
898 		return -E2BIG;
899 	if (!hlist_unhashed(&node->tramp_hlist))
900 		/* prog already linked */
901 		return -EBUSY;
902 	hlist_for_each_entry(node_existing, prog_list, tramp_hlist) {
903 		if (node_existing->link->prog != node->link->prog)
904 			continue;
905 		/* prog already linked */
906 		return -EBUSY;
907 	}
908 
909 	hlist_add_head(&node->tramp_hlist, prog_list);
910 	if (kind == BPF_TRAMP_FSESSION) {
911 		tr->progs_cnt[BPF_TRAMP_FENTRY]++;
912 		fexit = fsession_exit(node);
913 		if (WARN_ON_ONCE(!fexit))
914 			return -EINVAL;
915 		hlist_add_head(&fexit->tramp_hlist, &tr->progs_hlist[BPF_TRAMP_FEXIT]);
916 		tr->progs_cnt[BPF_TRAMP_FEXIT]++;
917 	} else {
918 		tr->progs_cnt[kind]++;
919 	}
920 	return 0;
921 }
922 
bpf_trampoline_remove_prog(struct bpf_trampoline * tr,struct bpf_tramp_node * node)923 static void bpf_trampoline_remove_prog(struct bpf_trampoline *tr,
924 				       struct bpf_tramp_node *node)
925 {
926 	enum bpf_tramp_prog_type kind;
927 	struct bpf_tramp_node *fexit;
928 
929 	kind = bpf_attach_type_to_tramp(node->link->prog);
930 	if (kind == BPF_TRAMP_FSESSION) {
931 		fexit = fsession_exit(node);
932 		if (WARN_ON_ONCE(!fexit))
933 			return;
934 		hlist_del_init(&fexit->tramp_hlist);
935 		tr->progs_cnt[BPF_TRAMP_FEXIT]--;
936 		kind = BPF_TRAMP_FENTRY;
937 	}
938 	hlist_del_init(&node->tramp_hlist);
939 	tr->progs_cnt[kind]--;
940 }
941 
__bpf_trampoline_link_prog(struct bpf_tramp_node * node,struct bpf_trampoline * tr,struct bpf_prog * tgt_prog,const struct bpf_trampoline_ops * ops,void * data)942 static int __bpf_trampoline_link_prog(struct bpf_tramp_node *node,
943 				      struct bpf_trampoline *tr,
944 				      struct bpf_prog *tgt_prog,
945 				      const struct bpf_trampoline_ops *ops,
946 				      void *data)
947 {
948 	enum bpf_tramp_prog_type kind;
949 	int err = 0;
950 	int cnt = 0, i;
951 
952 	kind = bpf_attach_type_to_tramp(node->link->prog);
953 	/*
954 	 * Arena ctx args are converted only by struct_ops indirect
955 	 * trampolines. They must never be attached to a generic trampoline.
956 	 */
957 	if (WARN_ON_ONCE(bpf_prog_has_arena_ctx_arg(node->link->prog)))
958 		return -ENOTSUPP;
959 
960 	if (tr->extension_prog)
961 		/* cannot attach fentry/fexit if extension prog is attached.
962 		 * cannot overwrite extension prog either.
963 		 */
964 		return -EBUSY;
965 
966 	for (i = 0; i < BPF_TRAMP_MAX; i++)
967 		cnt += tr->progs_cnt[i];
968 
969 	if (kind == BPF_TRAMP_REPLACE) {
970 		/* Cannot attach extension if fentry/fexit are in use. */
971 		if (cnt)
972 			return -EBUSY;
973 		err = bpf_freplace_check_tgt_prog(tgt_prog);
974 		if (err)
975 			return err;
976 		tr->extension_prog = node->link->prog;
977 		return bpf_arch_text_poke(tr->func.addr, BPF_MOD_NOP,
978 					  BPF_MOD_JUMP, NULL,
979 					  node->link->prog->bpf_func);
980 	}
981 	err = bpf_trampoline_add_prog(tr, node, cnt);
982 	if (err)
983 		return err;
984 	err = bpf_trampoline_update(tr, true /* lock_direct_mutex */, ops, data);
985 	if (err)
986 		bpf_trampoline_remove_prog(tr, node);
987 	return err;
988 }
989 
bpf_trampoline_link_prog(struct bpf_tramp_node * node,struct bpf_trampoline * tr,struct bpf_prog * tgt_prog)990 int bpf_trampoline_link_prog(struct bpf_tramp_node *node,
991 			     struct bpf_trampoline *tr,
992 			     struct bpf_prog *tgt_prog)
993 {
994 	int err;
995 
996 	trampoline_lock(tr);
997 	err = __bpf_trampoline_link_prog(node, tr, tgt_prog, &trampoline_ops, NULL);
998 	trampoline_unlock(tr);
999 	return err;
1000 }
1001 
__bpf_trampoline_unlink_prog(struct bpf_tramp_node * node,struct bpf_trampoline * tr,struct bpf_prog * tgt_prog,const struct bpf_trampoline_ops * ops,void * data)1002 static int __bpf_trampoline_unlink_prog(struct bpf_tramp_node *node,
1003 					struct bpf_trampoline *tr,
1004 					struct bpf_prog *tgt_prog,
1005 					const struct bpf_trampoline_ops *ops,
1006 					void *data)
1007 {
1008 	enum bpf_tramp_prog_type kind;
1009 	int err;
1010 
1011 	kind = bpf_attach_type_to_tramp(node->link->prog);
1012 	if (kind == BPF_TRAMP_REPLACE) {
1013 		WARN_ON_ONCE(!tr->extension_prog);
1014 		err = bpf_arch_text_poke(tr->func.addr, BPF_MOD_JUMP,
1015 					 BPF_MOD_NOP,
1016 					 tr->extension_prog->bpf_func, NULL);
1017 		tr->extension_prog = NULL;
1018 		guard(mutex)(&tgt_prog->aux->ext_mutex);
1019 		tgt_prog->aux->is_extended = false;
1020 		return err;
1021 	}
1022 	bpf_trampoline_remove_prog(tr, node);
1023 	return bpf_trampoline_update(tr, true /* lock_direct_mutex */, ops, data);
1024 }
1025 
1026 /* bpf_trampoline_unlink_prog() should never fail. */
bpf_trampoline_unlink_prog(struct bpf_tramp_node * node,struct bpf_trampoline * tr,struct bpf_prog * tgt_prog)1027 int bpf_trampoline_unlink_prog(struct bpf_tramp_node *node,
1028 			       struct bpf_trampoline *tr,
1029 			       struct bpf_prog *tgt_prog)
1030 {
1031 	int err;
1032 
1033 	trampoline_lock(tr);
1034 	err = __bpf_trampoline_unlink_prog(node, tr, tgt_prog, &trampoline_ops, NULL);
1035 	trampoline_unlock(tr);
1036 	return err;
1037 }
1038 
1039 #if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_BPF_LSM)
bpf_shim_tramp_link_release(struct bpf_link * link)1040 static void bpf_shim_tramp_link_release(struct bpf_link *link)
1041 {
1042 	struct bpf_shim_tramp_link *shim_link =
1043 		container_of(link, struct bpf_shim_tramp_link, link.link);
1044 	int err;
1045 
1046 	/* paired with 'shim_link->trampoline = tr' in bpf_trampoline_link_cgroup_shim */
1047 	if (!shim_link->trampoline)
1048 		return;
1049 
1050 	err = bpf_trampoline_unlink_prog(&shim_link->link.node, shim_link->trampoline, NULL);
1051 	WARN_ONCE(err, "bpf_trampoline_unlink_prog failed: %d\n", err);
1052 
1053 	bpf_trampoline_put(shim_link->trampoline);
1054 }
1055 
bpf_shim_tramp_link_dealloc(struct bpf_link * link)1056 static void bpf_shim_tramp_link_dealloc(struct bpf_link *link)
1057 {
1058 	struct bpf_shim_tramp_link *shim_link =
1059 		container_of(link, struct bpf_shim_tramp_link, link.link);
1060 
1061 	kfree(shim_link);
1062 }
1063 
1064 static const struct bpf_link_ops bpf_shim_tramp_link_lops = {
1065 	.release = bpf_shim_tramp_link_release,
1066 	.dealloc = bpf_shim_tramp_link_dealloc,
1067 };
1068 
cgroup_shim_alloc(const struct bpf_prog * prog,bpf_func_t bpf_func,int cgroup_atype,enum bpf_attach_type attach_type)1069 static struct bpf_shim_tramp_link *cgroup_shim_alloc(const struct bpf_prog *prog,
1070 						     bpf_func_t bpf_func,
1071 						     int cgroup_atype,
1072 						     enum bpf_attach_type attach_type)
1073 {
1074 	struct bpf_shim_tramp_link *shim_link = NULL;
1075 	struct bpf_prog *p;
1076 
1077 	shim_link = kzalloc_obj(*shim_link, GFP_USER);
1078 	if (!shim_link)
1079 		return NULL;
1080 
1081 	p = bpf_prog_alloc(1, 0);
1082 	if (!p) {
1083 		kfree(shim_link);
1084 		return NULL;
1085 	}
1086 
1087 	p->jited = false;
1088 	p->bpf_func = bpf_func;
1089 
1090 	p->aux->cgroup_atype = cgroup_atype;
1091 	p->aux->attach_func_proto = prog->aux->attach_func_proto;
1092 	p->aux->attach_btf_id = prog->aux->attach_btf_id;
1093 	p->aux->attach_btf = prog->aux->attach_btf;
1094 	btf_get(p->aux->attach_btf);
1095 	p->type = BPF_PROG_TYPE_LSM;
1096 	p->expected_attach_type = BPF_LSM_MAC;
1097 	bpf_prog_inc(p);
1098 	bpf_tramp_link_init(&shim_link->link, BPF_LINK_TYPE_UNSPEC,
1099 		      &bpf_shim_tramp_link_lops, p, attach_type, 0);
1100 	bpf_cgroup_atype_get(p->aux->attach_btf_id, cgroup_atype);
1101 
1102 	return shim_link;
1103 }
1104 
cgroup_shim_find(struct bpf_trampoline * tr,bpf_func_t bpf_func)1105 static struct bpf_shim_tramp_link *cgroup_shim_find(struct bpf_trampoline *tr,
1106 						    bpf_func_t bpf_func)
1107 {
1108 	struct bpf_tramp_node *node;
1109 	int kind;
1110 
1111 	for (kind = 0; kind < BPF_TRAMP_MAX; kind++) {
1112 		hlist_for_each_entry(node, &tr->progs_hlist[kind], tramp_hlist) {
1113 			struct bpf_prog *p = node->link->prog;
1114 
1115 			if (p->bpf_func == bpf_func)
1116 				return container_of(node, struct bpf_shim_tramp_link, link.node);
1117 		}
1118 	}
1119 
1120 	return NULL;
1121 }
1122 
bpf_trampoline_link_cgroup_shim(struct bpf_prog * prog,int cgroup_atype,enum bpf_attach_type attach_type)1123 int bpf_trampoline_link_cgroup_shim(struct bpf_prog *prog,
1124 				    int cgroup_atype,
1125 				    enum bpf_attach_type attach_type)
1126 {
1127 	struct bpf_shim_tramp_link *shim_link = NULL;
1128 	struct bpf_attach_target_info tgt_info = {};
1129 	struct bpf_trampoline *tr;
1130 	bpf_func_t bpf_func;
1131 	u64 key;
1132 	int err;
1133 
1134 	err = bpf_check_attach_target(NULL, prog, NULL,
1135 				      prog->aux->attach_btf_id,
1136 				      &tgt_info);
1137 	if (err)
1138 		return err;
1139 
1140 	key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf,
1141 					 prog->aux->attach_btf_id);
1142 
1143 	bpf_lsm_find_cgroup_shim(prog, &bpf_func);
1144 	tr = bpf_trampoline_get(key, &tgt_info);
1145 	if (!tr)
1146 		return  -ENOMEM;
1147 
1148 	trampoline_lock(tr);
1149 
1150 	shim_link = cgroup_shim_find(tr, bpf_func);
1151 	if (shim_link && !IS_ERR(bpf_link_inc_not_zero(&shim_link->link.link))) {
1152 		/* Reusing existing shim attached by the other program. */
1153 		trampoline_unlock(tr);
1154 		bpf_trampoline_put(tr); /* bpf_trampoline_get above */
1155 		return 0;
1156 	}
1157 
1158 	/* Allocate and install new shim. */
1159 
1160 	shim_link = cgroup_shim_alloc(prog, bpf_func, cgroup_atype, attach_type);
1161 	if (!shim_link) {
1162 		err = -ENOMEM;
1163 		goto err;
1164 	}
1165 
1166 	err = __bpf_trampoline_link_prog(&shim_link->link.node, tr, NULL, &trampoline_ops, NULL);
1167 	if (err)
1168 		goto err;
1169 
1170 	shim_link->trampoline = tr;
1171 	/* note, we're still holding tr refcnt from above */
1172 
1173 	trampoline_unlock(tr);
1174 
1175 	return 0;
1176 err:
1177 	trampoline_unlock(tr);
1178 
1179 	if (shim_link)
1180 		bpf_link_put(&shim_link->link.link);
1181 
1182 	/* have to release tr while _not_ holding pool mutex for trampoline */
1183 	bpf_trampoline_put(tr); /* bpf_trampoline_get above */
1184 
1185 	return err;
1186 }
1187 
bpf_trampoline_unlink_cgroup_shim(struct bpf_prog * prog)1188 void bpf_trampoline_unlink_cgroup_shim(struct bpf_prog *prog)
1189 {
1190 	struct bpf_shim_tramp_link *shim_link = NULL;
1191 	struct bpf_trampoline *tr;
1192 	bpf_func_t bpf_func;
1193 	u64 key;
1194 
1195 	key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf,
1196 					 prog->aux->attach_btf_id);
1197 
1198 	bpf_lsm_find_cgroup_shim(prog, &bpf_func);
1199 	tr = bpf_trampoline_lookup(key, 0);
1200 	if (WARN_ON_ONCE(!tr))
1201 		return;
1202 
1203 	trampoline_lock(tr);
1204 	shim_link = cgroup_shim_find(tr, bpf_func);
1205 	trampoline_unlock(tr);
1206 
1207 	if (shim_link)
1208 		bpf_link_put(&shim_link->link.link);
1209 
1210 	bpf_trampoline_put(tr); /* bpf_trampoline_lookup above */
1211 }
1212 #endif
1213 
bpf_trampoline_get(u64 key,struct bpf_attach_target_info * tgt_info)1214 struct bpf_trampoline *bpf_trampoline_get(u64 key,
1215 					  struct bpf_attach_target_info *tgt_info)
1216 {
1217 	struct bpf_trampoline *tr;
1218 
1219 	tr = bpf_trampoline_lookup(key, tgt_info->tgt_addr);
1220 	if (!tr)
1221 		return NULL;
1222 
1223 	trampoline_lock(tr);
1224 	if (tr->func.addr)
1225 		goto out;
1226 
1227 	memcpy(&tr->func.model, &tgt_info->fmodel, sizeof(tgt_info->fmodel));
1228 	tr->func.addr = (void *)tgt_info->tgt_addr;
1229 out:
1230 	trampoline_unlock(tr);
1231 	return tr;
1232 }
1233 
bpf_trampoline_put(struct bpf_trampoline * tr)1234 void bpf_trampoline_put(struct bpf_trampoline *tr)
1235 {
1236 	int i;
1237 
1238 	if (!tr)
1239 		return;
1240 	mutex_lock(&trampoline_mutex);
1241 	if (!refcount_dec_and_test(&tr->refcnt))
1242 		goto out;
1243 
1244 	for (i = 0; i < BPF_TRAMP_MAX; i++)
1245 		if (WARN_ON_ONCE(!hlist_empty(&tr->progs_hlist[i])))
1246 			goto out;
1247 
1248 	/* This code will be executed even when the last bpf_tramp_image
1249 	 * is alive. All progs are detached from the trampoline and the
1250 	 * trampoline image is patched with jmp into epilogue to skip
1251 	 * fexit progs. The fentry-only trampoline will be freed via
1252 	 * multiple rcu callbacks.
1253 	 */
1254 	hlist_del(&tr->hlist_key);
1255 	hlist_del(&tr->hlist_ip);
1256 	direct_ops_free(tr);
1257 	kfree(tr);
1258 out:
1259 	mutex_unlock(&trampoline_mutex);
1260 }
1261 
1262 #define NO_START_TIME 1
bpf_prog_start_time(void)1263 static __always_inline u64 notrace bpf_prog_start_time(void)
1264 {
1265 	u64 start = NO_START_TIME;
1266 
1267 	if (static_branch_unlikely(&bpf_stats_enabled_key)) {
1268 		start = sched_clock();
1269 		if (unlikely(!start))
1270 			start = NO_START_TIME;
1271 	}
1272 	return start;
1273 }
1274 
1275 /* The logic is similar to bpf_prog_run(), but with an explicit
1276  * rcu_read_lock() and migrate_disable() which are required
1277  * for the trampoline. The macro is split into
1278  * call __bpf_prog_enter
1279  * call prog->bpf_func
1280  * call __bpf_prog_exit
1281  *
1282  * __bpf_prog_enter returns:
1283  * 0 - skip execution of the bpf prog
1284  * 1 - execute bpf prog
1285  * [2..MAX_U64] - execute bpf prog and record execution time.
1286  *     This is start time.
1287  */
__bpf_prog_enter_recur(struct bpf_prog * prog,struct bpf_tramp_run_ctx * run_ctx)1288 static u64 notrace __bpf_prog_enter_recur(struct bpf_prog *prog, struct bpf_tramp_run_ctx *run_ctx)
1289 	__acquires(RCU)
1290 {
1291 	rcu_read_lock_dont_migrate();
1292 
1293 	run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
1294 
1295 	if (unlikely(!bpf_prog_get_recursion_context(prog))) {
1296 		bpf_prog_inc_misses_counter(prog);
1297 		if (prog->aux->recursion_detected)
1298 			prog->aux->recursion_detected(prog);
1299 		return 0;
1300 	}
1301 	return bpf_prog_start_time();
1302 }
1303 
__update_prog_stats(struct bpf_prog * prog,u64 start)1304 static void notrace __update_prog_stats(struct bpf_prog *prog, u64 start)
1305 {
1306 	struct bpf_prog_stats *stats;
1307 	unsigned long flags;
1308 	u64 duration;
1309 
1310 	/*
1311 	 * static_key could be enabled in __bpf_prog_enter* and disabled in
1312 	 * __bpf_prog_exit*. And vice versa. Check that 'start' is valid.
1313 	 */
1314 	if (start <= NO_START_TIME)
1315 		return;
1316 
1317 	duration = sched_clock() - start;
1318 	stats = this_cpu_ptr(prog->stats);
1319 	flags = u64_stats_update_begin_irqsave(&stats->syncp);
1320 	u64_stats_inc(&stats->cnt);
1321 	u64_stats_add(&stats->nsecs, duration);
1322 	u64_stats_update_end_irqrestore(&stats->syncp, flags);
1323 }
1324 
update_prog_stats(struct bpf_prog * prog,u64 start)1325 static __always_inline void notrace update_prog_stats(struct bpf_prog *prog,
1326 						      u64 start)
1327 {
1328 	if (static_branch_unlikely(&bpf_stats_enabled_key))
1329 		__update_prog_stats(prog, start);
1330 }
1331 
__bpf_prog_exit_recur(struct bpf_prog * prog,u64 start,struct bpf_tramp_run_ctx * run_ctx)1332 static void notrace __bpf_prog_exit_recur(struct bpf_prog *prog, u64 start,
1333 					  struct bpf_tramp_run_ctx *run_ctx)
1334 	__releases(RCU)
1335 {
1336 	bpf_reset_run_ctx(run_ctx->saved_run_ctx);
1337 
1338 	update_prog_stats(prog, start);
1339 	bpf_prog_put_recursion_context(prog);
1340 	rcu_read_unlock_migrate();
1341 }
1342 
__bpf_prog_enter_lsm_cgroup(struct bpf_prog * prog,struct bpf_tramp_run_ctx * run_ctx)1343 static u64 notrace __bpf_prog_enter_lsm_cgroup(struct bpf_prog *prog,
1344 					       struct bpf_tramp_run_ctx *run_ctx)
1345 	__acquires(RCU)
1346 {
1347 	/* Runtime stats are exported via actual BPF_LSM_CGROUP
1348 	 * programs, not the shims.
1349 	 */
1350 	rcu_read_lock_dont_migrate();
1351 
1352 	run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
1353 
1354 	return NO_START_TIME;
1355 }
1356 
__bpf_prog_exit_lsm_cgroup(struct bpf_prog * prog,u64 start,struct bpf_tramp_run_ctx * run_ctx)1357 static void notrace __bpf_prog_exit_lsm_cgroup(struct bpf_prog *prog, u64 start,
1358 					       struct bpf_tramp_run_ctx *run_ctx)
1359 	__releases(RCU)
1360 {
1361 	bpf_reset_run_ctx(run_ctx->saved_run_ctx);
1362 
1363 	rcu_read_unlock_migrate();
1364 }
1365 
__bpf_prog_enter_sleepable_recur(struct bpf_prog * prog,struct bpf_tramp_run_ctx * run_ctx)1366 u64 notrace __bpf_prog_enter_sleepable_recur(struct bpf_prog *prog,
1367 					     struct bpf_tramp_run_ctx *run_ctx)
1368 {
1369 	rcu_read_lock_trace();
1370 	migrate_disable();
1371 	might_fault();
1372 
1373 	run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
1374 
1375 	if (unlikely(!bpf_prog_get_recursion_context(prog))) {
1376 		bpf_prog_inc_misses_counter(prog);
1377 		if (prog->aux->recursion_detected)
1378 			prog->aux->recursion_detected(prog);
1379 		return 0;
1380 	}
1381 	return bpf_prog_start_time();
1382 }
1383 
__bpf_prog_exit_sleepable_recur(struct bpf_prog * prog,u64 start,struct bpf_tramp_run_ctx * run_ctx)1384 void notrace __bpf_prog_exit_sleepable_recur(struct bpf_prog *prog, u64 start,
1385 					     struct bpf_tramp_run_ctx *run_ctx)
1386 {
1387 	bpf_reset_run_ctx(run_ctx->saved_run_ctx);
1388 
1389 	update_prog_stats(prog, start);
1390 	bpf_prog_put_recursion_context(prog);
1391 	migrate_enable();
1392 	rcu_read_unlock_trace();
1393 }
1394 
__bpf_prog_enter_sleepable(struct bpf_prog * prog,struct bpf_tramp_run_ctx * run_ctx)1395 static u64 notrace __bpf_prog_enter_sleepable(struct bpf_prog *prog,
1396 					      struct bpf_tramp_run_ctx *run_ctx)
1397 {
1398 	rcu_read_lock_trace();
1399 	migrate_disable();
1400 	might_fault();
1401 
1402 	run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
1403 
1404 	return bpf_prog_start_time();
1405 }
1406 
__bpf_prog_exit_sleepable(struct bpf_prog * prog,u64 start,struct bpf_tramp_run_ctx * run_ctx)1407 static void notrace __bpf_prog_exit_sleepable(struct bpf_prog *prog, u64 start,
1408 					      struct bpf_tramp_run_ctx *run_ctx)
1409 {
1410 	bpf_reset_run_ctx(run_ctx->saved_run_ctx);
1411 
1412 	update_prog_stats(prog, start);
1413 	migrate_enable();
1414 	rcu_read_unlock_trace();
1415 }
1416 
__bpf_prog_enter(struct bpf_prog * prog,struct bpf_tramp_run_ctx * run_ctx)1417 static u64 notrace __bpf_prog_enter(struct bpf_prog *prog,
1418 				    struct bpf_tramp_run_ctx *run_ctx)
1419 	__acquires(RCU)
1420 {
1421 	rcu_read_lock_dont_migrate();
1422 
1423 	run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
1424 
1425 	return bpf_prog_start_time();
1426 }
1427 
__bpf_prog_exit(struct bpf_prog * prog,u64 start,struct bpf_tramp_run_ctx * run_ctx)1428 static void notrace __bpf_prog_exit(struct bpf_prog *prog, u64 start,
1429 				    struct bpf_tramp_run_ctx *run_ctx)
1430 	__releases(RCU)
1431 {
1432 	bpf_reset_run_ctx(run_ctx->saved_run_ctx);
1433 
1434 	update_prog_stats(prog, start);
1435 	rcu_read_unlock_migrate();
1436 }
1437 
__bpf_tramp_enter(struct bpf_tramp_image * tr)1438 void notrace __bpf_tramp_enter(struct bpf_tramp_image *tr)
1439 {
1440 	percpu_ref_get(&tr->pcref);
1441 }
1442 
__bpf_tramp_exit(struct bpf_tramp_image * tr)1443 void notrace __bpf_tramp_exit(struct bpf_tramp_image *tr)
1444 {
1445 	percpu_ref_put(&tr->pcref);
1446 }
1447 
bpf_trampoline_enter(const struct bpf_prog * prog)1448 bpf_trampoline_enter_t bpf_trampoline_enter(const struct bpf_prog *prog)
1449 {
1450 	bool sleepable = prog->sleepable;
1451 
1452 	if (bpf_prog_check_recur(prog))
1453 		return sleepable ? __bpf_prog_enter_sleepable_recur :
1454 			__bpf_prog_enter_recur;
1455 
1456 	if (resolve_prog_type(prog) == BPF_PROG_TYPE_LSM &&
1457 	    prog->expected_attach_type == BPF_LSM_CGROUP)
1458 		return __bpf_prog_enter_lsm_cgroup;
1459 
1460 	return sleepable ? __bpf_prog_enter_sleepable : __bpf_prog_enter;
1461 }
1462 
bpf_trampoline_exit(const struct bpf_prog * prog)1463 bpf_trampoline_exit_t bpf_trampoline_exit(const struct bpf_prog *prog)
1464 {
1465 	bool sleepable = prog->sleepable;
1466 
1467 	if (bpf_prog_check_recur(prog))
1468 		return sleepable ? __bpf_prog_exit_sleepable_recur :
1469 			__bpf_prog_exit_recur;
1470 
1471 	if (resolve_prog_type(prog) == BPF_PROG_TYPE_LSM &&
1472 	    prog->expected_attach_type == BPF_LSM_CGROUP)
1473 		return __bpf_prog_exit_lsm_cgroup;
1474 
1475 	return sleepable ? __bpf_prog_exit_sleepable : __bpf_prog_exit;
1476 }
1477 
1478 int __weak
arch_prepare_bpf_trampoline(struct bpf_tramp_image * im,void * image,void * image_end,const struct btf_func_model * m,u32 flags,struct bpf_tramp_nodes * tnodes,void * func_addr)1479 arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *image, void *image_end,
1480 			    const struct btf_func_model *m, u32 flags,
1481 			    struct bpf_tramp_nodes *tnodes,
1482 			    void *func_addr)
1483 {
1484 	return -ENOTSUPP;
1485 }
1486 
arch_alloc_bpf_trampoline(unsigned int size)1487 void * __weak arch_alloc_bpf_trampoline(unsigned int size)
1488 {
1489 	void *image;
1490 
1491 	if (WARN_ON_ONCE(size > PAGE_SIZE))
1492 		return NULL;
1493 	image = bpf_jit_alloc_exec(PAGE_SIZE);
1494 	if (image)
1495 		set_vm_flush_reset_perms(image);
1496 	return image;
1497 }
1498 
arch_free_bpf_trampoline(void * image,unsigned int size)1499 void __weak arch_free_bpf_trampoline(void *image, unsigned int size)
1500 {
1501 	WARN_ON_ONCE(size > PAGE_SIZE);
1502 	/* bpf_jit_free_exec doesn't need "size", but
1503 	 * bpf_prog_pack_free() needs it.
1504 	 */
1505 	bpf_jit_free_exec(image);
1506 }
1507 
arch_protect_bpf_trampoline(void * image,unsigned int size)1508 int __weak arch_protect_bpf_trampoline(void *image, unsigned int size)
1509 {
1510 	WARN_ON_ONCE(size > PAGE_SIZE);
1511 	return set_memory_rox((long)image, 1);
1512 }
1513 
arch_bpf_trampoline_size(const struct btf_func_model * m,u32 flags,struct bpf_tramp_nodes * tnodes,void * func_addr)1514 int __weak arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags,
1515 				    struct bpf_tramp_nodes *tnodes, void *func_addr)
1516 {
1517 	return -ENOTSUPP;
1518 }
1519 
1520 #if defined(CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS) && \
1521     defined(CONFIG_HAVE_SINGLE_FTRACE_DIRECT_OPS) && \
1522     defined(CONFIG_BPF_SYSCALL)
1523 
trampoline_lock_all(void)1524 static void trampoline_lock_all(void)
1525 {
1526 	int i;
1527 
1528 	for (i = 0; i < TRAMPOLINE_LOCKS_TABLE_SIZE; i++)
1529 		mutex_lock(&trampoline_locks[i].mutex);
1530 }
1531 
trampoline_unlock_all(void)1532 static void trampoline_unlock_all(void)
1533 {
1534 	int i;
1535 
1536 	for (i = 0; i < TRAMPOLINE_LOCKS_TABLE_SIZE; i++)
1537 		mutex_unlock(&trampoline_locks[i].mutex);
1538 }
1539 
remove_tracing_multi_data(struct bpf_tracing_multi_data * data)1540 static void remove_tracing_multi_data(struct bpf_tracing_multi_data *data)
1541 {
1542 	ftrace_hash_remove(data->reg);
1543 	ftrace_hash_remove(data->unreg);
1544 	ftrace_hash_remove(data->modify);
1545 }
1546 
clear_tracing_multi_data(struct bpf_tracing_multi_data * data)1547 static void clear_tracing_multi_data(struct bpf_tracing_multi_data *data)
1548 {
1549 	remove_tracing_multi_data(data);
1550 
1551 	free_ftrace_hash(data->reg);
1552 	free_ftrace_hash(data->unreg);
1553 	free_ftrace_hash(data->modify);
1554 }
1555 
init_tracing_multi_data(struct bpf_tracing_multi_data * data)1556 static int init_tracing_multi_data(struct bpf_tracing_multi_data *data)
1557 {
1558 	data->reg    = alloc_ftrace_hash(FTRACE_HASH_DEFAULT_BITS);
1559 	data->unreg  = alloc_ftrace_hash(FTRACE_HASH_DEFAULT_BITS);
1560 	data->modify = alloc_ftrace_hash(FTRACE_HASH_DEFAULT_BITS);
1561 
1562 	if (!data->reg || !data->unreg || !data->modify) {
1563 		clear_tracing_multi_data(data);
1564 		return -ENOMEM;
1565 	}
1566 	return 0;
1567 }
1568 
ftrace_hash_add(struct ftrace_hash * hash,struct ftrace_func_entry * entry,unsigned long ip,unsigned long direct)1569 static void ftrace_hash_add(struct ftrace_hash *hash, struct ftrace_func_entry *entry,
1570 			    unsigned long ip, unsigned long direct)
1571 {
1572 	entry->ip = ip;
1573 	entry->direct = direct;
1574 	add_ftrace_hash_entry(hash, entry);
1575 }
1576 
register_fentry_multi(struct bpf_trampoline * tr,struct bpf_tramp_image * im,void * ptr)1577 static int register_fentry_multi(struct bpf_trampoline *tr, struct bpf_tramp_image *im, void *ptr)
1578 {
1579 	unsigned long addr = (unsigned long) im->image;
1580 	unsigned long ip = ftrace_location(tr->ip);
1581 	struct bpf_tracing_multi_data *data = ptr;
1582 
1583 	if (bpf_trampoline_use_jmp(tr->flags))
1584 		addr = ftrace_jmp_set(addr);
1585 
1586 	tr->func.ftrace_managed = true;
1587 	ftrace_hash_add(data->reg, data->entry, ip, addr);
1588 	tr->cur_image = im;
1589 	return 0;
1590 }
1591 
unregister_fentry_multi(struct bpf_trampoline * tr,u32 orig_flags,void * ptr)1592 static int unregister_fentry_multi(struct bpf_trampoline *tr, u32 orig_flags, void *ptr)
1593 {
1594 	unsigned long addr = (unsigned long) tr->cur_image->image;
1595 	unsigned long ip = ftrace_location(tr->ip);
1596 	struct bpf_tracing_multi_data *data = ptr;
1597 
1598 	if (bpf_trampoline_use_jmp(tr->flags))
1599 		addr = ftrace_jmp_set(addr);
1600 
1601 	ftrace_hash_add(data->unreg, data->entry, ip, addr);
1602 	tr->cur_image = NULL;
1603 	return 0;
1604 }
1605 
modify_fentry_multi(struct bpf_trampoline * tr,u32 orig_flags,struct bpf_tramp_image * im,bool lock_direct_mutex,void * ptr)1606 static int modify_fentry_multi(struct bpf_trampoline *tr, u32 orig_flags, struct bpf_tramp_image *im,
1607 			       bool lock_direct_mutex, void *ptr)
1608 {
1609 	unsigned long addr = (unsigned long) im->image;
1610 	unsigned long ip = ftrace_location(tr->ip);
1611 	struct bpf_tracing_multi_data *data = ptr;
1612 
1613 	if (bpf_trampoline_use_jmp(tr->flags))
1614 		addr = ftrace_jmp_set(addr);
1615 
1616 	ftrace_hash_add(data->modify, data->entry, ip, addr);
1617 	tr->cur_image = im;
1618 	return 0;
1619 }
1620 
1621 static const struct bpf_trampoline_ops trampoline_multi_ops = {
1622 	.register_fentry   = register_fentry_multi,
1623 	.unregister_fentry = unregister_fentry_multi,
1624 	.modify_fentry     = modify_fentry_multi,
1625 };
1626 
bpf_trampoline_multi_attach_init(struct bpf_trampoline * tr)1627 static void bpf_trampoline_multi_attach_init(struct bpf_trampoline *tr)
1628 {
1629 	tr->multi_attach.old_image = tr->cur_image;
1630 	tr->multi_attach.old_flags = tr->flags;
1631 }
1632 
bpf_trampoline_multi_attach_free(struct bpf_trampoline * tr)1633 static void bpf_trampoline_multi_attach_free(struct bpf_trampoline *tr)
1634 {
1635 	/*
1636 	 * Only free old_image if it is no longer the active image.
1637 	 * When bpf_trampoline_update() fails before modify_fentry_multi()/
1638 	 * unregister_fentry_multi() is called, cur_image is unchanged
1639 	 * (cur_image == old_image) and ftrace still points to it. Freeing
1640 	 * it would cause a UAF when ftrace calls into the freed memory.
1641 	 * On success, cur_image is either a new image or NULL, so
1642 	 * old_image != cur_image means the image is stale.
1643 	 */
1644 	if (tr->multi_attach.old_image &&
1645 	    tr->multi_attach.old_image != tr->cur_image)
1646 		bpf_tramp_image_put(tr->multi_attach.old_image);
1647 
1648 	tr->multi_attach.old_image = NULL;
1649 	tr->multi_attach.old_flags = 0;
1650 }
1651 
bpf_trampoline_multi_attach_rollback(struct bpf_trampoline * tr)1652 static void bpf_trampoline_multi_attach_rollback(struct bpf_trampoline *tr)
1653 {
1654 	if (tr->cur_image)
1655 		bpf_tramp_image_put(tr->cur_image);
1656 	tr->cur_image = tr->multi_attach.old_image;
1657 	tr->flags = tr->multi_attach.old_flags;
1658 
1659 	tr->multi_attach.old_image = NULL;
1660 	tr->multi_attach.old_flags = 0;
1661 }
1662 
1663 #define for_each_mnode_cnt(mnode, link, cnt) \
1664 	for (i = 0, mnode = &link->nodes[i]; i < cnt; i++, mnode = &link->nodes[i])
1665 
1666 #define for_each_mnode(mnode, link) \
1667 	for_each_mnode_cnt(mnode, link, link->nodes_cnt)
1668 
bpf_trampoline_multi_attach(struct bpf_prog * prog,u32 * ids,struct bpf_tracing_multi_link * link)1669 int bpf_trampoline_multi_attach(struct bpf_prog *prog, u32 *ids,
1670 				struct bpf_tracing_multi_link *link)
1671 {
1672 	struct bpf_tracing_multi_data *data = &link->data;
1673 	struct bpf_attach_target_info tgt_info = {};
1674 	struct btf *btf = prog->aux->attach_btf;
1675 	struct bpf_tracing_multi_node *mnode;
1676 	struct bpf_trampoline *tr;
1677 	int i, err, rollback_cnt;
1678 	u64 key;
1679 
1680 	for_each_mnode(mnode, link) {
1681 		rollback_cnt = i;
1682 
1683 		err = bpf_check_attach_btf_id_multi(btf, prog, ids[i], &tgt_info);
1684 		if (err)
1685 			goto rollback_put;
1686 
1687 		key = bpf_trampoline_compute_key(NULL, btf, ids[i]);
1688 
1689 		tr = bpf_trampoline_get(key, &tgt_info);
1690 		if (!tr) {
1691 			err = -ENOMEM;
1692 			goto rollback_put;
1693 		}
1694 
1695 		mnode->trampoline = tr;
1696 		mnode->node.link = &link->link;
1697 		mnode->node.cookie = link->cookies ? link->cookies[i] : 0;
1698 
1699 		if (prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) {
1700 			link->fexits[i].link = &link->link;
1701 			link->fexits[i].cookie = link->cookies ? link->cookies[i] : 0;
1702 		}
1703 
1704 		cond_resched();
1705 	}
1706 
1707 	err = init_tracing_multi_data(data);
1708 	if (err) {
1709 		rollback_cnt = link->nodes_cnt;
1710 		goto rollback_put;
1711 	}
1712 
1713 	trampoline_lock_all();
1714 
1715 	for_each_mnode(mnode, link) {
1716 		bpf_trampoline_multi_attach_init(mnode->trampoline);
1717 
1718 		data->entry = &mnode->entry;
1719 		err = __bpf_trampoline_link_prog(&mnode->node, mnode->trampoline, NULL,
1720 						 &trampoline_multi_ops, data);
1721 		if (err) {
1722 			rollback_cnt = i;
1723 			goto rollback_unlink;
1724 		}
1725 	}
1726 
1727 	rollback_cnt = link->nodes_cnt;
1728 	if (ftrace_hash_count(data->reg)) {
1729 		err = update_ftrace_direct_add(&direct_ops, data->reg);
1730 		if (err)
1731 			goto rollback_unlink;
1732 	}
1733 
1734 	if (ftrace_hash_count(data->modify)) {
1735 		err = update_ftrace_direct_mod(&direct_ops, data->modify, true);
1736 		if (err) {
1737 			if (ftrace_hash_count(data->reg))
1738 				WARN_ON_ONCE(update_ftrace_direct_del(&direct_ops, data->reg));
1739 			goto rollback_unlink;
1740 		}
1741 	}
1742 
1743 	for_each_mnode(mnode, link)
1744 		bpf_trampoline_multi_attach_free(mnode->trampoline);
1745 
1746 	trampoline_unlock_all();
1747 
1748 	remove_tracing_multi_data(data);
1749 	return 0;
1750 
1751 rollback_unlink:
1752 	for_each_mnode_cnt(mnode, link, rollback_cnt) {
1753 		bpf_trampoline_remove_prog(mnode->trampoline, &mnode->node);
1754 		bpf_trampoline_multi_attach_rollback(mnode->trampoline);
1755 	}
1756 
1757 	trampoline_unlock_all();
1758 
1759 	clear_tracing_multi_data(data);
1760 	rollback_cnt = link->nodes_cnt;
1761 
1762 rollback_put:
1763 	for_each_mnode_cnt(mnode, link, rollback_cnt)
1764 		bpf_trampoline_put(mnode->trampoline);
1765 
1766 	return err;
1767 }
1768 
bpf_trampoline_multi_detach(struct bpf_prog * prog,struct bpf_tracing_multi_link * link)1769 void bpf_trampoline_multi_detach(struct bpf_prog *prog,
1770 				 struct bpf_tracing_multi_link *link)
1771 {
1772 	struct bpf_tracing_multi_data *data = &link->data;
1773 	struct bpf_tracing_multi_node *mnode;
1774 	int i, err;
1775 
1776 	trampoline_lock_all();
1777 
1778 	for_each_mnode(mnode, link) {
1779 		data->entry = &mnode->entry;
1780 		bpf_trampoline_multi_attach_init(mnode->trampoline);
1781 		err = __bpf_trampoline_unlink_prog(&mnode->node, mnode->trampoline, NULL,
1782 					&trampoline_multi_ops, data);
1783 		WARN_ONCE(err, "__bpf_trampoline_unlink_prog failed: %d\n", err);
1784 	}
1785 
1786 	if (ftrace_hash_count(data->unreg))
1787 		WARN_ON_ONCE(update_ftrace_direct_del(&direct_ops, data->unreg));
1788 	if (ftrace_hash_count(data->modify))
1789 		WARN_ON_ONCE(update_ftrace_direct_mod(&direct_ops, data->modify, true));
1790 
1791 	for_each_mnode(mnode, link)
1792 		bpf_trampoline_multi_attach_free(mnode->trampoline);
1793 
1794 	trampoline_unlock_all();
1795 
1796 	for_each_mnode(mnode, link)
1797 		bpf_trampoline_put(mnode->trampoline);
1798 
1799 	clear_tracing_multi_data(data);
1800 }
1801 
1802 #undef for_each_mnode_cnt
1803 #undef for_each_mnode
1804 
1805 #endif /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS &&
1806 	  CONFIG_HAVE_SINGLE_FTRACE_DIRECT_OPS &&
1807 	  CONFIG_BPF_SYSCALL */
1808 
init_trampolines(void)1809 static int __init init_trampolines(void)
1810 {
1811 	int i;
1812 
1813 	for (i = 0; i < TRAMPOLINE_TABLE_SIZE; i++)
1814 		INIT_HLIST_HEAD(&trampoline_key_table[i]);
1815 	for (i = 0; i < TRAMPOLINE_TABLE_SIZE; i++)
1816 		INIT_HLIST_HEAD(&trampoline_ip_table[i]);
1817 	for (i = 0; i < TRAMPOLINE_LOCKS_TABLE_SIZE; i++)
1818 		__mutex_init(&trampoline_locks[i].mutex, "trampoline_lock", &trampoline_locks[i].key);
1819 	return 0;
1820 }
1821 late_initcall(init_trampolines);
1822