xref: /linux/kernel/trace/bpf_trace.c (revision ab93e0dd72c37d378dd936f031ffb83ff2bd87ce)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2011-2015 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  */
5 #include <linux/kernel.h>
6 #include <linux/types.h>
7 #include <linux/slab.h>
8 #include <linux/bpf.h>
9 #include <linux/bpf_verifier.h>
10 #include <linux/bpf_perf_event.h>
11 #include <linux/btf.h>
12 #include <linux/filter.h>
13 #include <linux/uaccess.h>
14 #include <linux/ctype.h>
15 #include <linux/kprobes.h>
16 #include <linux/spinlock.h>
17 #include <linux/syscalls.h>
18 #include <linux/error-injection.h>
19 #include <linux/btf_ids.h>
20 #include <linux/bpf_lsm.h>
21 #include <linux/fprobe.h>
22 #include <linux/bsearch.h>
23 #include <linux/sort.h>
24 #include <linux/key.h>
25 #include <linux/verification.h>
26 #include <linux/namei.h>
27 
28 #include <net/bpf_sk_storage.h>
29 
30 #include <uapi/linux/bpf.h>
31 #include <uapi/linux/btf.h>
32 
33 #include <asm/tlb.h>
34 
35 #include "trace_probe.h"
36 #include "trace.h"
37 
38 #define CREATE_TRACE_POINTS
39 #include "bpf_trace.h"
40 
41 #define bpf_event_rcu_dereference(p)					\
42 	rcu_dereference_protected(p, lockdep_is_held(&bpf_event_mutex))
43 
44 #define MAX_UPROBE_MULTI_CNT (1U << 20)
45 #define MAX_KPROBE_MULTI_CNT (1U << 20)
46 
47 #ifdef CONFIG_MODULES
48 struct bpf_trace_module {
49 	struct module *module;
50 	struct list_head list;
51 };
52 
53 static LIST_HEAD(bpf_trace_modules);
54 static DEFINE_MUTEX(bpf_module_mutex);
55 
bpf_get_raw_tracepoint_module(const char * name)56 static struct bpf_raw_event_map *bpf_get_raw_tracepoint_module(const char *name)
57 {
58 	struct bpf_raw_event_map *btp, *ret = NULL;
59 	struct bpf_trace_module *btm;
60 	unsigned int i;
61 
62 	mutex_lock(&bpf_module_mutex);
63 	list_for_each_entry(btm, &bpf_trace_modules, list) {
64 		for (i = 0; i < btm->module->num_bpf_raw_events; ++i) {
65 			btp = &btm->module->bpf_raw_events[i];
66 			if (!strcmp(btp->tp->name, name)) {
67 				if (try_module_get(btm->module))
68 					ret = btp;
69 				goto out;
70 			}
71 		}
72 	}
73 out:
74 	mutex_unlock(&bpf_module_mutex);
75 	return ret;
76 }
77 #else
bpf_get_raw_tracepoint_module(const char * name)78 static struct bpf_raw_event_map *bpf_get_raw_tracepoint_module(const char *name)
79 {
80 	return NULL;
81 }
82 #endif /* CONFIG_MODULES */
83 
84 u64 bpf_get_stackid(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
85 u64 bpf_get_stack(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
86 
87 static int bpf_btf_printf_prepare(struct btf_ptr *ptr, u32 btf_ptr_size,
88 				  u64 flags, const struct btf **btf,
89 				  s32 *btf_id);
90 static u64 bpf_kprobe_multi_cookie(struct bpf_run_ctx *ctx);
91 static u64 bpf_kprobe_multi_entry_ip(struct bpf_run_ctx *ctx);
92 
93 static u64 bpf_uprobe_multi_cookie(struct bpf_run_ctx *ctx);
94 static u64 bpf_uprobe_multi_entry_ip(struct bpf_run_ctx *ctx);
95 
96 /**
97  * trace_call_bpf - invoke BPF program
98  * @call: tracepoint event
99  * @ctx: opaque context pointer
100  *
101  * kprobe handlers execute BPF programs via this helper.
102  * Can be used from static tracepoints in the future.
103  *
104  * Return: BPF programs always return an integer which is interpreted by
105  * kprobe handler as:
106  * 0 - return from kprobe (event is filtered out)
107  * 1 - store kprobe event into ring buffer
108  * Other values are reserved and currently alias to 1
109  */
trace_call_bpf(struct trace_event_call * call,void * ctx)110 unsigned int trace_call_bpf(struct trace_event_call *call, void *ctx)
111 {
112 	unsigned int ret;
113 
114 	cant_sleep();
115 
116 	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) {
117 		/*
118 		 * since some bpf program is already running on this cpu,
119 		 * don't call into another bpf program (same or different)
120 		 * and don't send kprobe event into ring-buffer,
121 		 * so return zero here
122 		 */
123 		rcu_read_lock();
124 		bpf_prog_inc_misses_counters(rcu_dereference(call->prog_array));
125 		rcu_read_unlock();
126 		ret = 0;
127 		goto out;
128 	}
129 
130 	/*
131 	 * Instead of moving rcu_read_lock/rcu_dereference/rcu_read_unlock
132 	 * to all call sites, we did a bpf_prog_array_valid() there to check
133 	 * whether call->prog_array is empty or not, which is
134 	 * a heuristic to speed up execution.
135 	 *
136 	 * If bpf_prog_array_valid() fetched prog_array was
137 	 * non-NULL, we go into trace_call_bpf() and do the actual
138 	 * proper rcu_dereference() under RCU lock.
139 	 * If it turns out that prog_array is NULL then, we bail out.
140 	 * For the opposite, if the bpf_prog_array_valid() fetched pointer
141 	 * was NULL, you'll skip the prog_array with the risk of missing
142 	 * out of events when it was updated in between this and the
143 	 * rcu_dereference() which is accepted risk.
144 	 */
145 	rcu_read_lock();
146 	ret = bpf_prog_run_array(rcu_dereference(call->prog_array),
147 				 ctx, bpf_prog_run);
148 	rcu_read_unlock();
149 
150  out:
151 	__this_cpu_dec(bpf_prog_active);
152 
153 	return ret;
154 }
155 
156 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
BPF_CALL_2(bpf_override_return,struct pt_regs *,regs,unsigned long,rc)157 BPF_CALL_2(bpf_override_return, struct pt_regs *, regs, unsigned long, rc)
158 {
159 	regs_set_return_value(regs, rc);
160 	override_function_with_return(regs);
161 	return 0;
162 }
163 
164 static const struct bpf_func_proto bpf_override_return_proto = {
165 	.func		= bpf_override_return,
166 	.gpl_only	= true,
167 	.ret_type	= RET_INTEGER,
168 	.arg1_type	= ARG_PTR_TO_CTX,
169 	.arg2_type	= ARG_ANYTHING,
170 };
171 #endif
172 
173 static __always_inline int
bpf_probe_read_user_common(void * dst,u32 size,const void __user * unsafe_ptr)174 bpf_probe_read_user_common(void *dst, u32 size, const void __user *unsafe_ptr)
175 {
176 	int ret;
177 
178 	ret = copy_from_user_nofault(dst, unsafe_ptr, size);
179 	if (unlikely(ret < 0))
180 		memset(dst, 0, size);
181 	return ret;
182 }
183 
BPF_CALL_3(bpf_probe_read_user,void *,dst,u32,size,const void __user *,unsafe_ptr)184 BPF_CALL_3(bpf_probe_read_user, void *, dst, u32, size,
185 	   const void __user *, unsafe_ptr)
186 {
187 	return bpf_probe_read_user_common(dst, size, unsafe_ptr);
188 }
189 
190 const struct bpf_func_proto bpf_probe_read_user_proto = {
191 	.func		= bpf_probe_read_user,
192 	.gpl_only	= true,
193 	.ret_type	= RET_INTEGER,
194 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
195 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
196 	.arg3_type	= ARG_ANYTHING,
197 };
198 
199 static __always_inline int
bpf_probe_read_user_str_common(void * dst,u32 size,const void __user * unsafe_ptr)200 bpf_probe_read_user_str_common(void *dst, u32 size,
201 			       const void __user *unsafe_ptr)
202 {
203 	int ret;
204 
205 	/*
206 	 * NB: We rely on strncpy_from_user() not copying junk past the NUL
207 	 * terminator into `dst`.
208 	 *
209 	 * strncpy_from_user() does long-sized strides in the fast path. If the
210 	 * strncpy does not mask out the bytes after the NUL in `unsafe_ptr`,
211 	 * then there could be junk after the NUL in `dst`. If user takes `dst`
212 	 * and keys a hash map with it, then semantically identical strings can
213 	 * occupy multiple entries in the map.
214 	 */
215 	ret = strncpy_from_user_nofault(dst, unsafe_ptr, size);
216 	if (unlikely(ret < 0))
217 		memset(dst, 0, size);
218 	return ret;
219 }
220 
BPF_CALL_3(bpf_probe_read_user_str,void *,dst,u32,size,const void __user *,unsafe_ptr)221 BPF_CALL_3(bpf_probe_read_user_str, void *, dst, u32, size,
222 	   const void __user *, unsafe_ptr)
223 {
224 	return bpf_probe_read_user_str_common(dst, size, unsafe_ptr);
225 }
226 
227 const struct bpf_func_proto bpf_probe_read_user_str_proto = {
228 	.func		= bpf_probe_read_user_str,
229 	.gpl_only	= true,
230 	.ret_type	= RET_INTEGER,
231 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
232 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
233 	.arg3_type	= ARG_ANYTHING,
234 };
235 
BPF_CALL_3(bpf_probe_read_kernel,void *,dst,u32,size,const void *,unsafe_ptr)236 BPF_CALL_3(bpf_probe_read_kernel, void *, dst, u32, size,
237 	   const void *, unsafe_ptr)
238 {
239 	return bpf_probe_read_kernel_common(dst, size, unsafe_ptr);
240 }
241 
242 const struct bpf_func_proto bpf_probe_read_kernel_proto = {
243 	.func		= bpf_probe_read_kernel,
244 	.gpl_only	= true,
245 	.ret_type	= RET_INTEGER,
246 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
247 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
248 	.arg3_type	= ARG_ANYTHING,
249 };
250 
251 static __always_inline int
bpf_probe_read_kernel_str_common(void * dst,u32 size,const void * unsafe_ptr)252 bpf_probe_read_kernel_str_common(void *dst, u32 size, const void *unsafe_ptr)
253 {
254 	int ret;
255 
256 	/*
257 	 * The strncpy_from_kernel_nofault() call will likely not fill the
258 	 * entire buffer, but that's okay in this circumstance as we're probing
259 	 * arbitrary memory anyway similar to bpf_probe_read_*() and might
260 	 * as well probe the stack. Thus, memory is explicitly cleared
261 	 * only in error case, so that improper users ignoring return
262 	 * code altogether don't copy garbage; otherwise length of string
263 	 * is returned that can be used for bpf_perf_event_output() et al.
264 	 */
265 	ret = strncpy_from_kernel_nofault(dst, unsafe_ptr, size);
266 	if (unlikely(ret < 0))
267 		memset(dst, 0, size);
268 	return ret;
269 }
270 
BPF_CALL_3(bpf_probe_read_kernel_str,void *,dst,u32,size,const void *,unsafe_ptr)271 BPF_CALL_3(bpf_probe_read_kernel_str, void *, dst, u32, size,
272 	   const void *, unsafe_ptr)
273 {
274 	return bpf_probe_read_kernel_str_common(dst, size, unsafe_ptr);
275 }
276 
277 const struct bpf_func_proto bpf_probe_read_kernel_str_proto = {
278 	.func		= bpf_probe_read_kernel_str,
279 	.gpl_only	= true,
280 	.ret_type	= RET_INTEGER,
281 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
282 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
283 	.arg3_type	= ARG_ANYTHING,
284 };
285 
286 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
BPF_CALL_3(bpf_probe_read_compat,void *,dst,u32,size,const void *,unsafe_ptr)287 BPF_CALL_3(bpf_probe_read_compat, void *, dst, u32, size,
288 	   const void *, unsafe_ptr)
289 {
290 	if ((unsigned long)unsafe_ptr < TASK_SIZE) {
291 		return bpf_probe_read_user_common(dst, size,
292 				(__force void __user *)unsafe_ptr);
293 	}
294 	return bpf_probe_read_kernel_common(dst, size, unsafe_ptr);
295 }
296 
297 static const struct bpf_func_proto bpf_probe_read_compat_proto = {
298 	.func		= bpf_probe_read_compat,
299 	.gpl_only	= true,
300 	.ret_type	= RET_INTEGER,
301 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
302 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
303 	.arg3_type	= ARG_ANYTHING,
304 };
305 
BPF_CALL_3(bpf_probe_read_compat_str,void *,dst,u32,size,const void *,unsafe_ptr)306 BPF_CALL_3(bpf_probe_read_compat_str, void *, dst, u32, size,
307 	   const void *, unsafe_ptr)
308 {
309 	if ((unsigned long)unsafe_ptr < TASK_SIZE) {
310 		return bpf_probe_read_user_str_common(dst, size,
311 				(__force void __user *)unsafe_ptr);
312 	}
313 	return bpf_probe_read_kernel_str_common(dst, size, unsafe_ptr);
314 }
315 
316 static const struct bpf_func_proto bpf_probe_read_compat_str_proto = {
317 	.func		= bpf_probe_read_compat_str,
318 	.gpl_only	= true,
319 	.ret_type	= RET_INTEGER,
320 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
321 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
322 	.arg3_type	= ARG_ANYTHING,
323 };
324 #endif /* CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE */
325 
BPF_CALL_3(bpf_probe_write_user,void __user *,unsafe_ptr,const void *,src,u32,size)326 BPF_CALL_3(bpf_probe_write_user, void __user *, unsafe_ptr, const void *, src,
327 	   u32, size)
328 {
329 	/*
330 	 * Ensure we're in user context which is safe for the helper to
331 	 * run. This helper has no business in a kthread.
332 	 *
333 	 * access_ok() should prevent writing to non-user memory, but in
334 	 * some situations (nommu, temporary switch, etc) access_ok() does
335 	 * not provide enough validation, hence the check on KERNEL_DS.
336 	 *
337 	 * nmi_uaccess_okay() ensures the probe is not run in an interim
338 	 * state, when the task or mm are switched. This is specifically
339 	 * required to prevent the use of temporary mm.
340 	 */
341 
342 	if (unlikely(in_interrupt() ||
343 		     current->flags & (PF_KTHREAD | PF_EXITING)))
344 		return -EPERM;
345 	if (unlikely(!nmi_uaccess_okay()))
346 		return -EPERM;
347 
348 	return copy_to_user_nofault(unsafe_ptr, src, size);
349 }
350 
351 static const struct bpf_func_proto bpf_probe_write_user_proto = {
352 	.func		= bpf_probe_write_user,
353 	.gpl_only	= true,
354 	.ret_type	= RET_INTEGER,
355 	.arg1_type	= ARG_ANYTHING,
356 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
357 	.arg3_type	= ARG_CONST_SIZE,
358 };
359 
360 #define MAX_TRACE_PRINTK_VARARGS	3
361 #define BPF_TRACE_PRINTK_SIZE		1024
362 
BPF_CALL_5(bpf_trace_printk,char *,fmt,u32,fmt_size,u64,arg1,u64,arg2,u64,arg3)363 BPF_CALL_5(bpf_trace_printk, char *, fmt, u32, fmt_size, u64, arg1,
364 	   u64, arg2, u64, arg3)
365 {
366 	u64 args[MAX_TRACE_PRINTK_VARARGS] = { arg1, arg2, arg3 };
367 	struct bpf_bprintf_data data = {
368 		.get_bin_args	= true,
369 		.get_buf	= true,
370 	};
371 	int ret;
372 
373 	ret = bpf_bprintf_prepare(fmt, fmt_size, args,
374 				  MAX_TRACE_PRINTK_VARARGS, &data);
375 	if (ret < 0)
376 		return ret;
377 
378 	ret = bstr_printf(data.buf, MAX_BPRINTF_BUF, fmt, data.bin_args);
379 
380 	trace_bpf_trace_printk(data.buf);
381 
382 	bpf_bprintf_cleanup(&data);
383 
384 	return ret;
385 }
386 
387 static const struct bpf_func_proto bpf_trace_printk_proto = {
388 	.func		= bpf_trace_printk,
389 	.gpl_only	= true,
390 	.ret_type	= RET_INTEGER,
391 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
392 	.arg2_type	= ARG_CONST_SIZE,
393 };
394 
__set_printk_clr_event(struct work_struct * work)395 static void __set_printk_clr_event(struct work_struct *work)
396 {
397 	/*
398 	 * This program might be calling bpf_trace_printk,
399 	 * so enable the associated bpf_trace/bpf_trace_printk event.
400 	 * Repeat this each time as it is possible a user has
401 	 * disabled bpf_trace_printk events.  By loading a program
402 	 * calling bpf_trace_printk() however the user has expressed
403 	 * the intent to see such events.
404 	 */
405 	if (trace_set_clr_event("bpf_trace", "bpf_trace_printk", 1))
406 		pr_warn_ratelimited("could not enable bpf_trace_printk events");
407 }
408 static DECLARE_WORK(set_printk_work, __set_printk_clr_event);
409 
bpf_get_trace_printk_proto(void)410 const struct bpf_func_proto *bpf_get_trace_printk_proto(void)
411 {
412 	schedule_work(&set_printk_work);
413 	return &bpf_trace_printk_proto;
414 }
415 
BPF_CALL_4(bpf_trace_vprintk,char *,fmt,u32,fmt_size,const void *,args,u32,data_len)416 BPF_CALL_4(bpf_trace_vprintk, char *, fmt, u32, fmt_size, const void *, args,
417 	   u32, data_len)
418 {
419 	struct bpf_bprintf_data data = {
420 		.get_bin_args	= true,
421 		.get_buf	= true,
422 	};
423 	int ret, num_args;
424 
425 	if (data_len & 7 || data_len > MAX_BPRINTF_VARARGS * 8 ||
426 	    (data_len && !args))
427 		return -EINVAL;
428 	num_args = data_len / 8;
429 
430 	ret = bpf_bprintf_prepare(fmt, fmt_size, args, num_args, &data);
431 	if (ret < 0)
432 		return ret;
433 
434 	ret = bstr_printf(data.buf, MAX_BPRINTF_BUF, fmt, data.bin_args);
435 
436 	trace_bpf_trace_printk(data.buf);
437 
438 	bpf_bprintf_cleanup(&data);
439 
440 	return ret;
441 }
442 
443 static const struct bpf_func_proto bpf_trace_vprintk_proto = {
444 	.func		= bpf_trace_vprintk,
445 	.gpl_only	= true,
446 	.ret_type	= RET_INTEGER,
447 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
448 	.arg2_type	= ARG_CONST_SIZE,
449 	.arg3_type	= ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
450 	.arg4_type	= ARG_CONST_SIZE_OR_ZERO,
451 };
452 
bpf_get_trace_vprintk_proto(void)453 const struct bpf_func_proto *bpf_get_trace_vprintk_proto(void)
454 {
455 	schedule_work(&set_printk_work);
456 	return &bpf_trace_vprintk_proto;
457 }
458 
BPF_CALL_5(bpf_seq_printf,struct seq_file *,m,char *,fmt,u32,fmt_size,const void *,args,u32,data_len)459 BPF_CALL_5(bpf_seq_printf, struct seq_file *, m, char *, fmt, u32, fmt_size,
460 	   const void *, args, u32, data_len)
461 {
462 	struct bpf_bprintf_data data = {
463 		.get_bin_args	= true,
464 	};
465 	int err, num_args;
466 
467 	if (data_len & 7 || data_len > MAX_BPRINTF_VARARGS * 8 ||
468 	    (data_len && !args))
469 		return -EINVAL;
470 	num_args = data_len / 8;
471 
472 	err = bpf_bprintf_prepare(fmt, fmt_size, args, num_args, &data);
473 	if (err < 0)
474 		return err;
475 
476 	seq_bprintf(m, fmt, data.bin_args);
477 
478 	bpf_bprintf_cleanup(&data);
479 
480 	return seq_has_overflowed(m) ? -EOVERFLOW : 0;
481 }
482 
483 BTF_ID_LIST_SINGLE(btf_seq_file_ids, struct, seq_file)
484 
485 static const struct bpf_func_proto bpf_seq_printf_proto = {
486 	.func		= bpf_seq_printf,
487 	.gpl_only	= true,
488 	.ret_type	= RET_INTEGER,
489 	.arg1_type	= ARG_PTR_TO_BTF_ID,
490 	.arg1_btf_id	= &btf_seq_file_ids[0],
491 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
492 	.arg3_type	= ARG_CONST_SIZE,
493 	.arg4_type      = ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
494 	.arg5_type      = ARG_CONST_SIZE_OR_ZERO,
495 };
496 
BPF_CALL_3(bpf_seq_write,struct seq_file *,m,const void *,data,u32,len)497 BPF_CALL_3(bpf_seq_write, struct seq_file *, m, const void *, data, u32, len)
498 {
499 	return seq_write(m, data, len) ? -EOVERFLOW : 0;
500 }
501 
502 static const struct bpf_func_proto bpf_seq_write_proto = {
503 	.func		= bpf_seq_write,
504 	.gpl_only	= true,
505 	.ret_type	= RET_INTEGER,
506 	.arg1_type	= ARG_PTR_TO_BTF_ID,
507 	.arg1_btf_id	= &btf_seq_file_ids[0],
508 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
509 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
510 };
511 
BPF_CALL_4(bpf_seq_printf_btf,struct seq_file *,m,struct btf_ptr *,ptr,u32,btf_ptr_size,u64,flags)512 BPF_CALL_4(bpf_seq_printf_btf, struct seq_file *, m, struct btf_ptr *, ptr,
513 	   u32, btf_ptr_size, u64, flags)
514 {
515 	const struct btf *btf;
516 	s32 btf_id;
517 	int ret;
518 
519 	ret = bpf_btf_printf_prepare(ptr, btf_ptr_size, flags, &btf, &btf_id);
520 	if (ret)
521 		return ret;
522 
523 	return btf_type_seq_show_flags(btf, btf_id, ptr->ptr, m, flags);
524 }
525 
526 static const struct bpf_func_proto bpf_seq_printf_btf_proto = {
527 	.func		= bpf_seq_printf_btf,
528 	.gpl_only	= true,
529 	.ret_type	= RET_INTEGER,
530 	.arg1_type	= ARG_PTR_TO_BTF_ID,
531 	.arg1_btf_id	= &btf_seq_file_ids[0],
532 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
533 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
534 	.arg4_type	= ARG_ANYTHING,
535 };
536 
537 static __always_inline int
get_map_perf_counter(struct bpf_map * map,u64 flags,u64 * value,u64 * enabled,u64 * running)538 get_map_perf_counter(struct bpf_map *map, u64 flags,
539 		     u64 *value, u64 *enabled, u64 *running)
540 {
541 	struct bpf_array *array = container_of(map, struct bpf_array, map);
542 	unsigned int cpu = smp_processor_id();
543 	u64 index = flags & BPF_F_INDEX_MASK;
544 	struct bpf_event_entry *ee;
545 
546 	if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
547 		return -EINVAL;
548 	if (index == BPF_F_CURRENT_CPU)
549 		index = cpu;
550 	if (unlikely(index >= array->map.max_entries))
551 		return -E2BIG;
552 
553 	ee = READ_ONCE(array->ptrs[index]);
554 	if (!ee)
555 		return -ENOENT;
556 
557 	return perf_event_read_local(ee->event, value, enabled, running);
558 }
559 
BPF_CALL_2(bpf_perf_event_read,struct bpf_map *,map,u64,flags)560 BPF_CALL_2(bpf_perf_event_read, struct bpf_map *, map, u64, flags)
561 {
562 	u64 value = 0;
563 	int err;
564 
565 	err = get_map_perf_counter(map, flags, &value, NULL, NULL);
566 	/*
567 	 * this api is ugly since we miss [-22..-2] range of valid
568 	 * counter values, but that's uapi
569 	 */
570 	if (err)
571 		return err;
572 	return value;
573 }
574 
575 const struct bpf_func_proto bpf_perf_event_read_proto = {
576 	.func		= bpf_perf_event_read,
577 	.gpl_only	= true,
578 	.ret_type	= RET_INTEGER,
579 	.arg1_type	= ARG_CONST_MAP_PTR,
580 	.arg2_type	= ARG_ANYTHING,
581 };
582 
BPF_CALL_4(bpf_perf_event_read_value,struct bpf_map *,map,u64,flags,struct bpf_perf_event_value *,buf,u32,size)583 BPF_CALL_4(bpf_perf_event_read_value, struct bpf_map *, map, u64, flags,
584 	   struct bpf_perf_event_value *, buf, u32, size)
585 {
586 	int err = -EINVAL;
587 
588 	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
589 		goto clear;
590 	err = get_map_perf_counter(map, flags, &buf->counter, &buf->enabled,
591 				   &buf->running);
592 	if (unlikely(err))
593 		goto clear;
594 	return 0;
595 clear:
596 	memset(buf, 0, size);
597 	return err;
598 }
599 
600 static const struct bpf_func_proto bpf_perf_event_read_value_proto = {
601 	.func		= bpf_perf_event_read_value,
602 	.gpl_only	= true,
603 	.ret_type	= RET_INTEGER,
604 	.arg1_type	= ARG_CONST_MAP_PTR,
605 	.arg2_type	= ARG_ANYTHING,
606 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
607 	.arg4_type	= ARG_CONST_SIZE,
608 };
609 
bpf_get_perf_event_read_value_proto(void)610 const struct bpf_func_proto *bpf_get_perf_event_read_value_proto(void)
611 {
612 	return &bpf_perf_event_read_value_proto;
613 }
614 
615 static __always_inline u64
__bpf_perf_event_output(struct pt_regs * regs,struct bpf_map * map,u64 flags,struct perf_raw_record * raw,struct perf_sample_data * sd)616 __bpf_perf_event_output(struct pt_regs *regs, struct bpf_map *map,
617 			u64 flags, struct perf_raw_record *raw,
618 			struct perf_sample_data *sd)
619 {
620 	struct bpf_array *array = container_of(map, struct bpf_array, map);
621 	unsigned int cpu = smp_processor_id();
622 	u64 index = flags & BPF_F_INDEX_MASK;
623 	struct bpf_event_entry *ee;
624 	struct perf_event *event;
625 
626 	if (index == BPF_F_CURRENT_CPU)
627 		index = cpu;
628 	if (unlikely(index >= array->map.max_entries))
629 		return -E2BIG;
630 
631 	ee = READ_ONCE(array->ptrs[index]);
632 	if (!ee)
633 		return -ENOENT;
634 
635 	event = ee->event;
636 	if (unlikely(event->attr.type != PERF_TYPE_SOFTWARE ||
637 		     event->attr.config != PERF_COUNT_SW_BPF_OUTPUT))
638 		return -EINVAL;
639 
640 	if (unlikely(event->oncpu != cpu))
641 		return -EOPNOTSUPP;
642 
643 	perf_sample_save_raw_data(sd, event, raw);
644 
645 	return perf_event_output(event, sd, regs);
646 }
647 
648 /*
649  * Support executing tracepoints in normal, irq, and nmi context that each call
650  * bpf_perf_event_output
651  */
652 struct bpf_trace_sample_data {
653 	struct perf_sample_data sds[3];
654 };
655 
656 static DEFINE_PER_CPU(struct bpf_trace_sample_data, bpf_trace_sds);
657 static DEFINE_PER_CPU(int, bpf_trace_nest_level);
BPF_CALL_5(bpf_perf_event_output,struct pt_regs *,regs,struct bpf_map *,map,u64,flags,void *,data,u64,size)658 BPF_CALL_5(bpf_perf_event_output, struct pt_regs *, regs, struct bpf_map *, map,
659 	   u64, flags, void *, data, u64, size)
660 {
661 	struct bpf_trace_sample_data *sds;
662 	struct perf_raw_record raw = {
663 		.frag = {
664 			.size = size,
665 			.data = data,
666 		},
667 	};
668 	struct perf_sample_data *sd;
669 	int nest_level, err;
670 
671 	preempt_disable();
672 	sds = this_cpu_ptr(&bpf_trace_sds);
673 	nest_level = this_cpu_inc_return(bpf_trace_nest_level);
674 
675 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(sds->sds))) {
676 		err = -EBUSY;
677 		goto out;
678 	}
679 
680 	sd = &sds->sds[nest_level - 1];
681 
682 	if (unlikely(flags & ~(BPF_F_INDEX_MASK))) {
683 		err = -EINVAL;
684 		goto out;
685 	}
686 
687 	perf_sample_data_init(sd, 0, 0);
688 
689 	err = __bpf_perf_event_output(regs, map, flags, &raw, sd);
690 out:
691 	this_cpu_dec(bpf_trace_nest_level);
692 	preempt_enable();
693 	return err;
694 }
695 
696 static const struct bpf_func_proto bpf_perf_event_output_proto = {
697 	.func		= bpf_perf_event_output,
698 	.gpl_only	= true,
699 	.ret_type	= RET_INTEGER,
700 	.arg1_type	= ARG_PTR_TO_CTX,
701 	.arg2_type	= ARG_CONST_MAP_PTR,
702 	.arg3_type	= ARG_ANYTHING,
703 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
704 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
705 };
706 
707 static DEFINE_PER_CPU(int, bpf_event_output_nest_level);
708 struct bpf_nested_pt_regs {
709 	struct pt_regs regs[3];
710 };
711 static DEFINE_PER_CPU(struct bpf_nested_pt_regs, bpf_pt_regs);
712 static DEFINE_PER_CPU(struct bpf_trace_sample_data, bpf_misc_sds);
713 
bpf_event_output(struct bpf_map * map,u64 flags,void * meta,u64 meta_size,void * ctx,u64 ctx_size,bpf_ctx_copy_t ctx_copy)714 u64 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
715 		     void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
716 {
717 	struct perf_raw_frag frag = {
718 		.copy		= ctx_copy,
719 		.size		= ctx_size,
720 		.data		= ctx,
721 	};
722 	struct perf_raw_record raw = {
723 		.frag = {
724 			{
725 				.next	= ctx_size ? &frag : NULL,
726 			},
727 			.size	= meta_size,
728 			.data	= meta,
729 		},
730 	};
731 	struct perf_sample_data *sd;
732 	struct pt_regs *regs;
733 	int nest_level;
734 	u64 ret;
735 
736 	preempt_disable();
737 	nest_level = this_cpu_inc_return(bpf_event_output_nest_level);
738 
739 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(bpf_misc_sds.sds))) {
740 		ret = -EBUSY;
741 		goto out;
742 	}
743 	sd = this_cpu_ptr(&bpf_misc_sds.sds[nest_level - 1]);
744 	regs = this_cpu_ptr(&bpf_pt_regs.regs[nest_level - 1]);
745 
746 	perf_fetch_caller_regs(regs);
747 	perf_sample_data_init(sd, 0, 0);
748 
749 	ret = __bpf_perf_event_output(regs, map, flags, &raw, sd);
750 out:
751 	this_cpu_dec(bpf_event_output_nest_level);
752 	preempt_enable();
753 	return ret;
754 }
755 
BPF_CALL_0(bpf_get_current_task)756 BPF_CALL_0(bpf_get_current_task)
757 {
758 	return (long) current;
759 }
760 
761 const struct bpf_func_proto bpf_get_current_task_proto = {
762 	.func		= bpf_get_current_task,
763 	.gpl_only	= true,
764 	.ret_type	= RET_INTEGER,
765 };
766 
BPF_CALL_0(bpf_get_current_task_btf)767 BPF_CALL_0(bpf_get_current_task_btf)
768 {
769 	return (unsigned long) current;
770 }
771 
772 const struct bpf_func_proto bpf_get_current_task_btf_proto = {
773 	.func		= bpf_get_current_task_btf,
774 	.gpl_only	= true,
775 	.ret_type	= RET_PTR_TO_BTF_ID_TRUSTED,
776 	.ret_btf_id	= &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
777 };
778 
BPF_CALL_1(bpf_task_pt_regs,struct task_struct *,task)779 BPF_CALL_1(bpf_task_pt_regs, struct task_struct *, task)
780 {
781 	return (unsigned long) task_pt_regs(task);
782 }
783 
784 BTF_ID_LIST_SINGLE(bpf_task_pt_regs_ids, struct, pt_regs)
785 
786 const struct bpf_func_proto bpf_task_pt_regs_proto = {
787 	.func		= bpf_task_pt_regs,
788 	.gpl_only	= true,
789 	.arg1_type	= ARG_PTR_TO_BTF_ID,
790 	.arg1_btf_id	= &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
791 	.ret_type	= RET_PTR_TO_BTF_ID,
792 	.ret_btf_id	= &bpf_task_pt_regs_ids[0],
793 };
794 
795 struct send_signal_irq_work {
796 	struct irq_work irq_work;
797 	struct task_struct *task;
798 	u32 sig;
799 	enum pid_type type;
800 	bool has_siginfo;
801 	struct kernel_siginfo info;
802 };
803 
804 static DEFINE_PER_CPU(struct send_signal_irq_work, send_signal_work);
805 
do_bpf_send_signal(struct irq_work * entry)806 static void do_bpf_send_signal(struct irq_work *entry)
807 {
808 	struct send_signal_irq_work *work;
809 	struct kernel_siginfo *siginfo;
810 
811 	work = container_of(entry, struct send_signal_irq_work, irq_work);
812 	siginfo = work->has_siginfo ? &work->info : SEND_SIG_PRIV;
813 
814 	group_send_sig_info(work->sig, siginfo, work->task, work->type);
815 	put_task_struct(work->task);
816 }
817 
bpf_send_signal_common(u32 sig,enum pid_type type,struct task_struct * task,u64 value)818 static int bpf_send_signal_common(u32 sig, enum pid_type type, struct task_struct *task, u64 value)
819 {
820 	struct send_signal_irq_work *work = NULL;
821 	struct kernel_siginfo info;
822 	struct kernel_siginfo *siginfo;
823 
824 	if (!task) {
825 		task = current;
826 		siginfo = SEND_SIG_PRIV;
827 	} else {
828 		clear_siginfo(&info);
829 		info.si_signo = sig;
830 		info.si_errno = 0;
831 		info.si_code = SI_KERNEL;
832 		info.si_pid = 0;
833 		info.si_uid = 0;
834 		info.si_value.sival_ptr = (void *)(unsigned long)value;
835 		siginfo = &info;
836 	}
837 
838 	/* Similar to bpf_probe_write_user, task needs to be
839 	 * in a sound condition and kernel memory access be
840 	 * permitted in order to send signal to the current
841 	 * task.
842 	 */
843 	if (unlikely(task->flags & (PF_KTHREAD | PF_EXITING)))
844 		return -EPERM;
845 	if (unlikely(!nmi_uaccess_okay()))
846 		return -EPERM;
847 	/* Task should not be pid=1 to avoid kernel panic. */
848 	if (unlikely(is_global_init(task)))
849 		return -EPERM;
850 
851 	if (preempt_count() != 0 || irqs_disabled()) {
852 		/* Do an early check on signal validity. Otherwise,
853 		 * the error is lost in deferred irq_work.
854 		 */
855 		if (unlikely(!valid_signal(sig)))
856 			return -EINVAL;
857 
858 		work = this_cpu_ptr(&send_signal_work);
859 		if (irq_work_is_busy(&work->irq_work))
860 			return -EBUSY;
861 
862 		/* Add the current task, which is the target of sending signal,
863 		 * to the irq_work. The current task may change when queued
864 		 * irq works get executed.
865 		 */
866 		work->task = get_task_struct(task);
867 		work->has_siginfo = siginfo == &info;
868 		if (work->has_siginfo)
869 			copy_siginfo(&work->info, &info);
870 		work->sig = sig;
871 		work->type = type;
872 		irq_work_queue(&work->irq_work);
873 		return 0;
874 	}
875 
876 	return group_send_sig_info(sig, siginfo, task, type);
877 }
878 
BPF_CALL_1(bpf_send_signal,u32,sig)879 BPF_CALL_1(bpf_send_signal, u32, sig)
880 {
881 	return bpf_send_signal_common(sig, PIDTYPE_TGID, NULL, 0);
882 }
883 
884 const struct bpf_func_proto bpf_send_signal_proto = {
885 	.func		= bpf_send_signal,
886 	.gpl_only	= false,
887 	.ret_type	= RET_INTEGER,
888 	.arg1_type	= ARG_ANYTHING,
889 };
890 
BPF_CALL_1(bpf_send_signal_thread,u32,sig)891 BPF_CALL_1(bpf_send_signal_thread, u32, sig)
892 {
893 	return bpf_send_signal_common(sig, PIDTYPE_PID, NULL, 0);
894 }
895 
896 const struct bpf_func_proto bpf_send_signal_thread_proto = {
897 	.func		= bpf_send_signal_thread,
898 	.gpl_only	= false,
899 	.ret_type	= RET_INTEGER,
900 	.arg1_type	= ARG_ANYTHING,
901 };
902 
BPF_CALL_3(bpf_d_path,struct path *,path,char *,buf,u32,sz)903 BPF_CALL_3(bpf_d_path, struct path *, path, char *, buf, u32, sz)
904 {
905 	struct path copy;
906 	long len;
907 	char *p;
908 
909 	if (!sz)
910 		return 0;
911 
912 	/*
913 	 * The path pointer is verified as trusted and safe to use,
914 	 * but let's double check it's valid anyway to workaround
915 	 * potentially broken verifier.
916 	 */
917 	len = copy_from_kernel_nofault(&copy, path, sizeof(*path));
918 	if (len < 0)
919 		return len;
920 
921 	p = d_path(&copy, buf, sz);
922 	if (IS_ERR(p)) {
923 		len = PTR_ERR(p);
924 	} else {
925 		len = buf + sz - p;
926 		memmove(buf, p, len);
927 	}
928 
929 	return len;
930 }
931 
932 BTF_SET_START(btf_allowlist_d_path)
933 #ifdef CONFIG_SECURITY
BTF_ID(func,security_file_permission)934 BTF_ID(func, security_file_permission)
935 BTF_ID(func, security_inode_getattr)
936 BTF_ID(func, security_file_open)
937 #endif
938 #ifdef CONFIG_SECURITY_PATH
939 BTF_ID(func, security_path_truncate)
940 #endif
941 BTF_ID(func, vfs_truncate)
942 BTF_ID(func, vfs_fallocate)
943 BTF_ID(func, dentry_open)
944 BTF_ID(func, vfs_getattr)
945 BTF_ID(func, filp_close)
946 BTF_SET_END(btf_allowlist_d_path)
947 
948 static bool bpf_d_path_allowed(const struct bpf_prog *prog)
949 {
950 	if (prog->type == BPF_PROG_TYPE_TRACING &&
951 	    prog->expected_attach_type == BPF_TRACE_ITER)
952 		return true;
953 
954 	if (prog->type == BPF_PROG_TYPE_LSM)
955 		return bpf_lsm_is_sleepable_hook(prog->aux->attach_btf_id);
956 
957 	return btf_id_set_contains(&btf_allowlist_d_path,
958 				   prog->aux->attach_btf_id);
959 }
960 
961 BTF_ID_LIST_SINGLE(bpf_d_path_btf_ids, struct, path)
962 
963 static const struct bpf_func_proto bpf_d_path_proto = {
964 	.func		= bpf_d_path,
965 	.gpl_only	= false,
966 	.ret_type	= RET_INTEGER,
967 	.arg1_type	= ARG_PTR_TO_BTF_ID,
968 	.arg1_btf_id	= &bpf_d_path_btf_ids[0],
969 	.arg2_type	= ARG_PTR_TO_MEM,
970 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
971 	.allowed	= bpf_d_path_allowed,
972 };
973 
974 #define BTF_F_ALL	(BTF_F_COMPACT  | BTF_F_NONAME | \
975 			 BTF_F_PTR_RAW | BTF_F_ZERO)
976 
bpf_btf_printf_prepare(struct btf_ptr * ptr,u32 btf_ptr_size,u64 flags,const struct btf ** btf,s32 * btf_id)977 static int bpf_btf_printf_prepare(struct btf_ptr *ptr, u32 btf_ptr_size,
978 				  u64 flags, const struct btf **btf,
979 				  s32 *btf_id)
980 {
981 	const struct btf_type *t;
982 
983 	if (unlikely(flags & ~(BTF_F_ALL)))
984 		return -EINVAL;
985 
986 	if (btf_ptr_size != sizeof(struct btf_ptr))
987 		return -EINVAL;
988 
989 	*btf = bpf_get_btf_vmlinux();
990 
991 	if (IS_ERR_OR_NULL(*btf))
992 		return IS_ERR(*btf) ? PTR_ERR(*btf) : -EINVAL;
993 
994 	if (ptr->type_id > 0)
995 		*btf_id = ptr->type_id;
996 	else
997 		return -EINVAL;
998 
999 	if (*btf_id > 0)
1000 		t = btf_type_by_id(*btf, *btf_id);
1001 	if (*btf_id <= 0 || !t)
1002 		return -ENOENT;
1003 
1004 	return 0;
1005 }
1006 
BPF_CALL_5(bpf_snprintf_btf,char *,str,u32,str_size,struct btf_ptr *,ptr,u32,btf_ptr_size,u64,flags)1007 BPF_CALL_5(bpf_snprintf_btf, char *, str, u32, str_size, struct btf_ptr *, ptr,
1008 	   u32, btf_ptr_size, u64, flags)
1009 {
1010 	const struct btf *btf;
1011 	s32 btf_id;
1012 	int ret;
1013 
1014 	ret = bpf_btf_printf_prepare(ptr, btf_ptr_size, flags, &btf, &btf_id);
1015 	if (ret)
1016 		return ret;
1017 
1018 	return btf_type_snprintf_show(btf, btf_id, ptr->ptr, str, str_size,
1019 				      flags);
1020 }
1021 
1022 const struct bpf_func_proto bpf_snprintf_btf_proto = {
1023 	.func		= bpf_snprintf_btf,
1024 	.gpl_only	= false,
1025 	.ret_type	= RET_INTEGER,
1026 	.arg1_type	= ARG_PTR_TO_MEM,
1027 	.arg2_type	= ARG_CONST_SIZE,
1028 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1029 	.arg4_type	= ARG_CONST_SIZE,
1030 	.arg5_type	= ARG_ANYTHING,
1031 };
1032 
BPF_CALL_1(bpf_get_func_ip_tracing,void *,ctx)1033 BPF_CALL_1(bpf_get_func_ip_tracing, void *, ctx)
1034 {
1035 	/* This helper call is inlined by verifier. */
1036 	return ((u64 *)ctx)[-2];
1037 }
1038 
1039 static const struct bpf_func_proto bpf_get_func_ip_proto_tracing = {
1040 	.func		= bpf_get_func_ip_tracing,
1041 	.gpl_only	= true,
1042 	.ret_type	= RET_INTEGER,
1043 	.arg1_type	= ARG_PTR_TO_CTX,
1044 };
1045 
get_entry_ip(unsigned long fentry_ip)1046 static inline unsigned long get_entry_ip(unsigned long fentry_ip)
1047 {
1048 #ifdef CONFIG_X86_KERNEL_IBT
1049 	if (is_endbr((void *)(fentry_ip - ENDBR_INSN_SIZE)))
1050 		fentry_ip -= ENDBR_INSN_SIZE;
1051 #endif
1052 	return fentry_ip;
1053 }
1054 
BPF_CALL_1(bpf_get_func_ip_kprobe,struct pt_regs *,regs)1055 BPF_CALL_1(bpf_get_func_ip_kprobe, struct pt_regs *, regs)
1056 {
1057 	struct bpf_trace_run_ctx *run_ctx __maybe_unused;
1058 	struct kprobe *kp;
1059 
1060 #ifdef CONFIG_UPROBES
1061 	run_ctx = container_of(current->bpf_ctx, struct bpf_trace_run_ctx, run_ctx);
1062 	if (run_ctx->is_uprobe)
1063 		return ((struct uprobe_dispatch_data *)current->utask->vaddr)->bp_addr;
1064 #endif
1065 
1066 	kp = kprobe_running();
1067 
1068 	if (!kp || !(kp->flags & KPROBE_FLAG_ON_FUNC_ENTRY))
1069 		return 0;
1070 
1071 	return get_entry_ip((uintptr_t)kp->addr);
1072 }
1073 
1074 static const struct bpf_func_proto bpf_get_func_ip_proto_kprobe = {
1075 	.func		= bpf_get_func_ip_kprobe,
1076 	.gpl_only	= true,
1077 	.ret_type	= RET_INTEGER,
1078 	.arg1_type	= ARG_PTR_TO_CTX,
1079 };
1080 
BPF_CALL_1(bpf_get_func_ip_kprobe_multi,struct pt_regs *,regs)1081 BPF_CALL_1(bpf_get_func_ip_kprobe_multi, struct pt_regs *, regs)
1082 {
1083 	return bpf_kprobe_multi_entry_ip(current->bpf_ctx);
1084 }
1085 
1086 static const struct bpf_func_proto bpf_get_func_ip_proto_kprobe_multi = {
1087 	.func		= bpf_get_func_ip_kprobe_multi,
1088 	.gpl_only	= false,
1089 	.ret_type	= RET_INTEGER,
1090 	.arg1_type	= ARG_PTR_TO_CTX,
1091 };
1092 
BPF_CALL_1(bpf_get_attach_cookie_kprobe_multi,struct pt_regs *,regs)1093 BPF_CALL_1(bpf_get_attach_cookie_kprobe_multi, struct pt_regs *, regs)
1094 {
1095 	return bpf_kprobe_multi_cookie(current->bpf_ctx);
1096 }
1097 
1098 static const struct bpf_func_proto bpf_get_attach_cookie_proto_kmulti = {
1099 	.func		= bpf_get_attach_cookie_kprobe_multi,
1100 	.gpl_only	= false,
1101 	.ret_type	= RET_INTEGER,
1102 	.arg1_type	= ARG_PTR_TO_CTX,
1103 };
1104 
BPF_CALL_1(bpf_get_func_ip_uprobe_multi,struct pt_regs *,regs)1105 BPF_CALL_1(bpf_get_func_ip_uprobe_multi, struct pt_regs *, regs)
1106 {
1107 	return bpf_uprobe_multi_entry_ip(current->bpf_ctx);
1108 }
1109 
1110 static const struct bpf_func_proto bpf_get_func_ip_proto_uprobe_multi = {
1111 	.func		= bpf_get_func_ip_uprobe_multi,
1112 	.gpl_only	= false,
1113 	.ret_type	= RET_INTEGER,
1114 	.arg1_type	= ARG_PTR_TO_CTX,
1115 };
1116 
BPF_CALL_1(bpf_get_attach_cookie_uprobe_multi,struct pt_regs *,regs)1117 BPF_CALL_1(bpf_get_attach_cookie_uprobe_multi, struct pt_regs *, regs)
1118 {
1119 	return bpf_uprobe_multi_cookie(current->bpf_ctx);
1120 }
1121 
1122 static const struct bpf_func_proto bpf_get_attach_cookie_proto_umulti = {
1123 	.func		= bpf_get_attach_cookie_uprobe_multi,
1124 	.gpl_only	= false,
1125 	.ret_type	= RET_INTEGER,
1126 	.arg1_type	= ARG_PTR_TO_CTX,
1127 };
1128 
BPF_CALL_1(bpf_get_attach_cookie_trace,void *,ctx)1129 BPF_CALL_1(bpf_get_attach_cookie_trace, void *, ctx)
1130 {
1131 	struct bpf_trace_run_ctx *run_ctx;
1132 
1133 	run_ctx = container_of(current->bpf_ctx, struct bpf_trace_run_ctx, run_ctx);
1134 	return run_ctx->bpf_cookie;
1135 }
1136 
1137 static const struct bpf_func_proto bpf_get_attach_cookie_proto_trace = {
1138 	.func		= bpf_get_attach_cookie_trace,
1139 	.gpl_only	= false,
1140 	.ret_type	= RET_INTEGER,
1141 	.arg1_type	= ARG_PTR_TO_CTX,
1142 };
1143 
BPF_CALL_1(bpf_get_attach_cookie_pe,struct bpf_perf_event_data_kern *,ctx)1144 BPF_CALL_1(bpf_get_attach_cookie_pe, struct bpf_perf_event_data_kern *, ctx)
1145 {
1146 	return ctx->event->bpf_cookie;
1147 }
1148 
1149 static const struct bpf_func_proto bpf_get_attach_cookie_proto_pe = {
1150 	.func		= bpf_get_attach_cookie_pe,
1151 	.gpl_only	= false,
1152 	.ret_type	= RET_INTEGER,
1153 	.arg1_type	= ARG_PTR_TO_CTX,
1154 };
1155 
BPF_CALL_1(bpf_get_attach_cookie_tracing,void *,ctx)1156 BPF_CALL_1(bpf_get_attach_cookie_tracing, void *, ctx)
1157 {
1158 	struct bpf_trace_run_ctx *run_ctx;
1159 
1160 	run_ctx = container_of(current->bpf_ctx, struct bpf_trace_run_ctx, run_ctx);
1161 	return run_ctx->bpf_cookie;
1162 }
1163 
1164 static const struct bpf_func_proto bpf_get_attach_cookie_proto_tracing = {
1165 	.func		= bpf_get_attach_cookie_tracing,
1166 	.gpl_only	= false,
1167 	.ret_type	= RET_INTEGER,
1168 	.arg1_type	= ARG_PTR_TO_CTX,
1169 };
1170 
BPF_CALL_3(bpf_get_branch_snapshot,void *,buf,u32,size,u64,flags)1171 BPF_CALL_3(bpf_get_branch_snapshot, void *, buf, u32, size, u64, flags)
1172 {
1173 	static const u32 br_entry_size = sizeof(struct perf_branch_entry);
1174 	u32 entry_cnt = size / br_entry_size;
1175 
1176 	entry_cnt = static_call(perf_snapshot_branch_stack)(buf, entry_cnt);
1177 
1178 	if (unlikely(flags))
1179 		return -EINVAL;
1180 
1181 	if (!entry_cnt)
1182 		return -ENOENT;
1183 
1184 	return entry_cnt * br_entry_size;
1185 }
1186 
1187 const struct bpf_func_proto bpf_get_branch_snapshot_proto = {
1188 	.func		= bpf_get_branch_snapshot,
1189 	.gpl_only	= true,
1190 	.ret_type	= RET_INTEGER,
1191 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
1192 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
1193 };
1194 
BPF_CALL_3(get_func_arg,void *,ctx,u32,n,u64 *,value)1195 BPF_CALL_3(get_func_arg, void *, ctx, u32, n, u64 *, value)
1196 {
1197 	/* This helper call is inlined by verifier. */
1198 	u64 nr_args = ((u64 *)ctx)[-1];
1199 
1200 	if ((u64) n >= nr_args)
1201 		return -EINVAL;
1202 	*value = ((u64 *)ctx)[n];
1203 	return 0;
1204 }
1205 
1206 static const struct bpf_func_proto bpf_get_func_arg_proto = {
1207 	.func		= get_func_arg,
1208 	.ret_type	= RET_INTEGER,
1209 	.arg1_type	= ARG_PTR_TO_CTX,
1210 	.arg2_type	= ARG_ANYTHING,
1211 	.arg3_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED,
1212 	.arg3_size	= sizeof(u64),
1213 };
1214 
BPF_CALL_2(get_func_ret,void *,ctx,u64 *,value)1215 BPF_CALL_2(get_func_ret, void *, ctx, u64 *, value)
1216 {
1217 	/* This helper call is inlined by verifier. */
1218 	u64 nr_args = ((u64 *)ctx)[-1];
1219 
1220 	*value = ((u64 *)ctx)[nr_args];
1221 	return 0;
1222 }
1223 
1224 static const struct bpf_func_proto bpf_get_func_ret_proto = {
1225 	.func		= get_func_ret,
1226 	.ret_type	= RET_INTEGER,
1227 	.arg1_type	= ARG_PTR_TO_CTX,
1228 	.arg2_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED,
1229 	.arg2_size	= sizeof(u64),
1230 };
1231 
BPF_CALL_1(get_func_arg_cnt,void *,ctx)1232 BPF_CALL_1(get_func_arg_cnt, void *, ctx)
1233 {
1234 	/* This helper call is inlined by verifier. */
1235 	return ((u64 *)ctx)[-1];
1236 }
1237 
1238 static const struct bpf_func_proto bpf_get_func_arg_cnt_proto = {
1239 	.func		= get_func_arg_cnt,
1240 	.ret_type	= RET_INTEGER,
1241 	.arg1_type	= ARG_PTR_TO_CTX,
1242 };
1243 
1244 #ifdef CONFIG_KEYS
1245 __bpf_kfunc_start_defs();
1246 
1247 /**
1248  * bpf_lookup_user_key - lookup a key by its serial
1249  * @serial: key handle serial number
1250  * @flags: lookup-specific flags
1251  *
1252  * Search a key with a given *serial* and the provided *flags*.
1253  * If found, increment the reference count of the key by one, and
1254  * return it in the bpf_key structure.
1255  *
1256  * The bpf_key structure must be passed to bpf_key_put() when done
1257  * with it, so that the key reference count is decremented and the
1258  * bpf_key structure is freed.
1259  *
1260  * Permission checks are deferred to the time the key is used by
1261  * one of the available key-specific kfuncs.
1262  *
1263  * Set *flags* with KEY_LOOKUP_CREATE, to attempt creating a requested
1264  * special keyring (e.g. session keyring), if it doesn't yet exist.
1265  * Set *flags* with KEY_LOOKUP_PARTIAL, to lookup a key without waiting
1266  * for the key construction, and to retrieve uninstantiated keys (keys
1267  * without data attached to them).
1268  *
1269  * Return: a bpf_key pointer with a valid key pointer if the key is found, a
1270  *         NULL pointer otherwise.
1271  */
bpf_lookup_user_key(s32 serial,u64 flags)1272 __bpf_kfunc struct bpf_key *bpf_lookup_user_key(s32 serial, u64 flags)
1273 {
1274 	key_ref_t key_ref;
1275 	struct bpf_key *bkey;
1276 
1277 	if (flags & ~KEY_LOOKUP_ALL)
1278 		return NULL;
1279 
1280 	/*
1281 	 * Permission check is deferred until the key is used, as the
1282 	 * intent of the caller is unknown here.
1283 	 */
1284 	key_ref = lookup_user_key(serial, flags, KEY_DEFER_PERM_CHECK);
1285 	if (IS_ERR(key_ref))
1286 		return NULL;
1287 
1288 	bkey = kmalloc(sizeof(*bkey), GFP_KERNEL);
1289 	if (!bkey) {
1290 		key_put(key_ref_to_ptr(key_ref));
1291 		return NULL;
1292 	}
1293 
1294 	bkey->key = key_ref_to_ptr(key_ref);
1295 	bkey->has_ref = true;
1296 
1297 	return bkey;
1298 }
1299 
1300 /**
1301  * bpf_lookup_system_key - lookup a key by a system-defined ID
1302  * @id: key ID
1303  *
1304  * Obtain a bpf_key structure with a key pointer set to the passed key ID.
1305  * The key pointer is marked as invalid, to prevent bpf_key_put() from
1306  * attempting to decrement the key reference count on that pointer. The key
1307  * pointer set in such way is currently understood only by
1308  * verify_pkcs7_signature().
1309  *
1310  * Set *id* to one of the values defined in include/linux/verification.h:
1311  * 0 for the primary keyring (immutable keyring of system keys);
1312  * VERIFY_USE_SECONDARY_KEYRING for both the primary and secondary keyring
1313  * (where keys can be added only if they are vouched for by existing keys
1314  * in those keyrings); VERIFY_USE_PLATFORM_KEYRING for the platform
1315  * keyring (primarily used by the integrity subsystem to verify a kexec'ed
1316  * kerned image and, possibly, the initramfs signature).
1317  *
1318  * Return: a bpf_key pointer with an invalid key pointer set from the
1319  *         pre-determined ID on success, a NULL pointer otherwise
1320  */
bpf_lookup_system_key(u64 id)1321 __bpf_kfunc struct bpf_key *bpf_lookup_system_key(u64 id)
1322 {
1323 	struct bpf_key *bkey;
1324 
1325 	if (system_keyring_id_check(id) < 0)
1326 		return NULL;
1327 
1328 	bkey = kmalloc(sizeof(*bkey), GFP_ATOMIC);
1329 	if (!bkey)
1330 		return NULL;
1331 
1332 	bkey->key = (struct key *)(unsigned long)id;
1333 	bkey->has_ref = false;
1334 
1335 	return bkey;
1336 }
1337 
1338 /**
1339  * bpf_key_put - decrement key reference count if key is valid and free bpf_key
1340  * @bkey: bpf_key structure
1341  *
1342  * Decrement the reference count of the key inside *bkey*, if the pointer
1343  * is valid, and free *bkey*.
1344  */
bpf_key_put(struct bpf_key * bkey)1345 __bpf_kfunc void bpf_key_put(struct bpf_key *bkey)
1346 {
1347 	if (bkey->has_ref)
1348 		key_put(bkey->key);
1349 
1350 	kfree(bkey);
1351 }
1352 
1353 #ifdef CONFIG_SYSTEM_DATA_VERIFICATION
1354 /**
1355  * bpf_verify_pkcs7_signature - verify a PKCS#7 signature
1356  * @data_p: data to verify
1357  * @sig_p: signature of the data
1358  * @trusted_keyring: keyring with keys trusted for signature verification
1359  *
1360  * Verify the PKCS#7 signature *sig_ptr* against the supplied *data_ptr*
1361  * with keys in a keyring referenced by *trusted_keyring*.
1362  *
1363  * Return: 0 on success, a negative value on error.
1364  */
bpf_verify_pkcs7_signature(struct bpf_dynptr * data_p,struct bpf_dynptr * sig_p,struct bpf_key * trusted_keyring)1365 __bpf_kfunc int bpf_verify_pkcs7_signature(struct bpf_dynptr *data_p,
1366 			       struct bpf_dynptr *sig_p,
1367 			       struct bpf_key *trusted_keyring)
1368 {
1369 	struct bpf_dynptr_kern *data_ptr = (struct bpf_dynptr_kern *)data_p;
1370 	struct bpf_dynptr_kern *sig_ptr = (struct bpf_dynptr_kern *)sig_p;
1371 	const void *data, *sig;
1372 	u32 data_len, sig_len;
1373 	int ret;
1374 
1375 	if (trusted_keyring->has_ref) {
1376 		/*
1377 		 * Do the permission check deferred in bpf_lookup_user_key().
1378 		 * See bpf_lookup_user_key() for more details.
1379 		 *
1380 		 * A call to key_task_permission() here would be redundant, as
1381 		 * it is already done by keyring_search() called by
1382 		 * find_asymmetric_key().
1383 		 */
1384 		ret = key_validate(trusted_keyring->key);
1385 		if (ret < 0)
1386 			return ret;
1387 	}
1388 
1389 	data_len = __bpf_dynptr_size(data_ptr);
1390 	data = __bpf_dynptr_data(data_ptr, data_len);
1391 	sig_len = __bpf_dynptr_size(sig_ptr);
1392 	sig = __bpf_dynptr_data(sig_ptr, sig_len);
1393 
1394 	return verify_pkcs7_signature(data, data_len, sig, sig_len,
1395 				      trusted_keyring->key,
1396 				      VERIFYING_UNSPECIFIED_SIGNATURE, NULL,
1397 				      NULL);
1398 }
1399 #endif /* CONFIG_SYSTEM_DATA_VERIFICATION */
1400 
1401 __bpf_kfunc_end_defs();
1402 
1403 BTF_KFUNCS_START(key_sig_kfunc_set)
1404 BTF_ID_FLAGS(func, bpf_lookup_user_key, KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE)
1405 BTF_ID_FLAGS(func, bpf_lookup_system_key, KF_ACQUIRE | KF_RET_NULL)
1406 BTF_ID_FLAGS(func, bpf_key_put, KF_RELEASE)
1407 #ifdef CONFIG_SYSTEM_DATA_VERIFICATION
1408 BTF_ID_FLAGS(func, bpf_verify_pkcs7_signature, KF_SLEEPABLE)
1409 #endif
1410 BTF_KFUNCS_END(key_sig_kfunc_set)
1411 
1412 static const struct btf_kfunc_id_set bpf_key_sig_kfunc_set = {
1413 	.owner = THIS_MODULE,
1414 	.set = &key_sig_kfunc_set,
1415 };
1416 
bpf_key_sig_kfuncs_init(void)1417 static int __init bpf_key_sig_kfuncs_init(void)
1418 {
1419 	return register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
1420 					 &bpf_key_sig_kfunc_set);
1421 }
1422 
1423 late_initcall(bpf_key_sig_kfuncs_init);
1424 #endif /* CONFIG_KEYS */
1425 
1426 static const struct bpf_func_proto *
bpf_tracing_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)1427 bpf_tracing_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1428 {
1429 	const struct bpf_func_proto *func_proto;
1430 
1431 	switch (func_id) {
1432 	case BPF_FUNC_get_smp_processor_id:
1433 		return &bpf_get_smp_processor_id_proto;
1434 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
1435 	case BPF_FUNC_probe_read:
1436 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1437 		       NULL : &bpf_probe_read_compat_proto;
1438 	case BPF_FUNC_probe_read_str:
1439 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1440 		       NULL : &bpf_probe_read_compat_str_proto;
1441 #endif
1442 	case BPF_FUNC_get_func_ip:
1443 		return &bpf_get_func_ip_proto_tracing;
1444 	default:
1445 		break;
1446 	}
1447 
1448 	func_proto = bpf_base_func_proto(func_id, prog);
1449 	if (func_proto)
1450 		return func_proto;
1451 
1452 	if (!bpf_token_capable(prog->aux->token, CAP_SYS_ADMIN))
1453 		return NULL;
1454 
1455 	switch (func_id) {
1456 	case BPF_FUNC_probe_write_user:
1457 		return security_locked_down(LOCKDOWN_BPF_WRITE_USER) < 0 ?
1458 		       NULL : &bpf_probe_write_user_proto;
1459 	default:
1460 		return NULL;
1461 	}
1462 }
1463 
is_kprobe_multi(const struct bpf_prog * prog)1464 static bool is_kprobe_multi(const struct bpf_prog *prog)
1465 {
1466 	return prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI ||
1467 	       prog->expected_attach_type == BPF_TRACE_KPROBE_SESSION;
1468 }
1469 
is_kprobe_session(const struct bpf_prog * prog)1470 static inline bool is_kprobe_session(const struct bpf_prog *prog)
1471 {
1472 	return prog->expected_attach_type == BPF_TRACE_KPROBE_SESSION;
1473 }
1474 
is_uprobe_multi(const struct bpf_prog * prog)1475 static inline bool is_uprobe_multi(const struct bpf_prog *prog)
1476 {
1477 	return prog->expected_attach_type == BPF_TRACE_UPROBE_MULTI ||
1478 	       prog->expected_attach_type == BPF_TRACE_UPROBE_SESSION;
1479 }
1480 
is_uprobe_session(const struct bpf_prog * prog)1481 static inline bool is_uprobe_session(const struct bpf_prog *prog)
1482 {
1483 	return prog->expected_attach_type == BPF_TRACE_UPROBE_SESSION;
1484 }
1485 
1486 static const struct bpf_func_proto *
kprobe_prog_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)1487 kprobe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1488 {
1489 	switch (func_id) {
1490 	case BPF_FUNC_perf_event_output:
1491 		return &bpf_perf_event_output_proto;
1492 	case BPF_FUNC_get_stackid:
1493 		return &bpf_get_stackid_proto;
1494 	case BPF_FUNC_get_stack:
1495 		return prog->sleepable ? &bpf_get_stack_sleepable_proto : &bpf_get_stack_proto;
1496 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
1497 	case BPF_FUNC_override_return:
1498 		return &bpf_override_return_proto;
1499 #endif
1500 	case BPF_FUNC_get_func_ip:
1501 		if (is_kprobe_multi(prog))
1502 			return &bpf_get_func_ip_proto_kprobe_multi;
1503 		if (is_uprobe_multi(prog))
1504 			return &bpf_get_func_ip_proto_uprobe_multi;
1505 		return &bpf_get_func_ip_proto_kprobe;
1506 	case BPF_FUNC_get_attach_cookie:
1507 		if (is_kprobe_multi(prog))
1508 			return &bpf_get_attach_cookie_proto_kmulti;
1509 		if (is_uprobe_multi(prog))
1510 			return &bpf_get_attach_cookie_proto_umulti;
1511 		return &bpf_get_attach_cookie_proto_trace;
1512 	default:
1513 		return bpf_tracing_func_proto(func_id, prog);
1514 	}
1515 }
1516 
1517 /* bpf+kprobe programs can access fields of 'struct pt_regs' */
kprobe_prog_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)1518 static bool kprobe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1519 					const struct bpf_prog *prog,
1520 					struct bpf_insn_access_aux *info)
1521 {
1522 	if (off < 0 || off >= sizeof(struct pt_regs))
1523 		return false;
1524 	if (type != BPF_READ)
1525 		return false;
1526 	if (off % size != 0)
1527 		return false;
1528 	/*
1529 	 * Assertion for 32 bit to make sure last 8 byte access
1530 	 * (BPF_DW) to the last 4 byte member is disallowed.
1531 	 */
1532 	if (off + size > sizeof(struct pt_regs))
1533 		return false;
1534 
1535 	return true;
1536 }
1537 
1538 const struct bpf_verifier_ops kprobe_verifier_ops = {
1539 	.get_func_proto  = kprobe_prog_func_proto,
1540 	.is_valid_access = kprobe_prog_is_valid_access,
1541 };
1542 
1543 const struct bpf_prog_ops kprobe_prog_ops = {
1544 };
1545 
BPF_CALL_5(bpf_perf_event_output_tp,void *,tp_buff,struct bpf_map *,map,u64,flags,void *,data,u64,size)1546 BPF_CALL_5(bpf_perf_event_output_tp, void *, tp_buff, struct bpf_map *, map,
1547 	   u64, flags, void *, data, u64, size)
1548 {
1549 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1550 
1551 	/*
1552 	 * r1 points to perf tracepoint buffer where first 8 bytes are hidden
1553 	 * from bpf program and contain a pointer to 'struct pt_regs'. Fetch it
1554 	 * from there and call the same bpf_perf_event_output() helper inline.
1555 	 */
1556 	return ____bpf_perf_event_output(regs, map, flags, data, size);
1557 }
1558 
1559 static const struct bpf_func_proto bpf_perf_event_output_proto_tp = {
1560 	.func		= bpf_perf_event_output_tp,
1561 	.gpl_only	= true,
1562 	.ret_type	= RET_INTEGER,
1563 	.arg1_type	= ARG_PTR_TO_CTX,
1564 	.arg2_type	= ARG_CONST_MAP_PTR,
1565 	.arg3_type	= ARG_ANYTHING,
1566 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1567 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
1568 };
1569 
BPF_CALL_3(bpf_get_stackid_tp,void *,tp_buff,struct bpf_map *,map,u64,flags)1570 BPF_CALL_3(bpf_get_stackid_tp, void *, tp_buff, struct bpf_map *, map,
1571 	   u64, flags)
1572 {
1573 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1574 
1575 	/*
1576 	 * Same comment as in bpf_perf_event_output_tp(), only that this time
1577 	 * the other helper's function body cannot be inlined due to being
1578 	 * external, thus we need to call raw helper function.
1579 	 */
1580 	return bpf_get_stackid((unsigned long) regs, (unsigned long) map,
1581 			       flags, 0, 0);
1582 }
1583 
1584 static const struct bpf_func_proto bpf_get_stackid_proto_tp = {
1585 	.func		= bpf_get_stackid_tp,
1586 	.gpl_only	= true,
1587 	.ret_type	= RET_INTEGER,
1588 	.arg1_type	= ARG_PTR_TO_CTX,
1589 	.arg2_type	= ARG_CONST_MAP_PTR,
1590 	.arg3_type	= ARG_ANYTHING,
1591 };
1592 
BPF_CALL_4(bpf_get_stack_tp,void *,tp_buff,void *,buf,u32,size,u64,flags)1593 BPF_CALL_4(bpf_get_stack_tp, void *, tp_buff, void *, buf, u32, size,
1594 	   u64, flags)
1595 {
1596 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1597 
1598 	return bpf_get_stack((unsigned long) regs, (unsigned long) buf,
1599 			     (unsigned long) size, flags, 0);
1600 }
1601 
1602 static const struct bpf_func_proto bpf_get_stack_proto_tp = {
1603 	.func		= bpf_get_stack_tp,
1604 	.gpl_only	= true,
1605 	.ret_type	= RET_INTEGER,
1606 	.arg1_type	= ARG_PTR_TO_CTX,
1607 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
1608 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
1609 	.arg4_type	= ARG_ANYTHING,
1610 };
1611 
1612 static const struct bpf_func_proto *
tp_prog_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)1613 tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1614 {
1615 	switch (func_id) {
1616 	case BPF_FUNC_perf_event_output:
1617 		return &bpf_perf_event_output_proto_tp;
1618 	case BPF_FUNC_get_stackid:
1619 		return &bpf_get_stackid_proto_tp;
1620 	case BPF_FUNC_get_stack:
1621 		return &bpf_get_stack_proto_tp;
1622 	case BPF_FUNC_get_attach_cookie:
1623 		return &bpf_get_attach_cookie_proto_trace;
1624 	default:
1625 		return bpf_tracing_func_proto(func_id, prog);
1626 	}
1627 }
1628 
tp_prog_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)1629 static bool tp_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1630 				    const struct bpf_prog *prog,
1631 				    struct bpf_insn_access_aux *info)
1632 {
1633 	if (off < sizeof(void *) || off >= PERF_MAX_TRACE_SIZE)
1634 		return false;
1635 	if (type != BPF_READ)
1636 		return false;
1637 	if (off % size != 0)
1638 		return false;
1639 
1640 	BUILD_BUG_ON(PERF_MAX_TRACE_SIZE % sizeof(__u64));
1641 	return true;
1642 }
1643 
1644 const struct bpf_verifier_ops tracepoint_verifier_ops = {
1645 	.get_func_proto  = tp_prog_func_proto,
1646 	.is_valid_access = tp_prog_is_valid_access,
1647 };
1648 
1649 const struct bpf_prog_ops tracepoint_prog_ops = {
1650 };
1651 
BPF_CALL_3(bpf_perf_prog_read_value,struct bpf_perf_event_data_kern *,ctx,struct bpf_perf_event_value *,buf,u32,size)1652 BPF_CALL_3(bpf_perf_prog_read_value, struct bpf_perf_event_data_kern *, ctx,
1653 	   struct bpf_perf_event_value *, buf, u32, size)
1654 {
1655 	int err = -EINVAL;
1656 
1657 	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
1658 		goto clear;
1659 	err = perf_event_read_local(ctx->event, &buf->counter, &buf->enabled,
1660 				    &buf->running);
1661 	if (unlikely(err))
1662 		goto clear;
1663 	return 0;
1664 clear:
1665 	memset(buf, 0, size);
1666 	return err;
1667 }
1668 
1669 static const struct bpf_func_proto bpf_perf_prog_read_value_proto = {
1670          .func           = bpf_perf_prog_read_value,
1671          .gpl_only       = true,
1672          .ret_type       = RET_INTEGER,
1673          .arg1_type      = ARG_PTR_TO_CTX,
1674          .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
1675          .arg3_type      = ARG_CONST_SIZE,
1676 };
1677 
BPF_CALL_4(bpf_read_branch_records,struct bpf_perf_event_data_kern *,ctx,void *,buf,u32,size,u64,flags)1678 BPF_CALL_4(bpf_read_branch_records, struct bpf_perf_event_data_kern *, ctx,
1679 	   void *, buf, u32, size, u64, flags)
1680 {
1681 	static const u32 br_entry_size = sizeof(struct perf_branch_entry);
1682 	struct perf_branch_stack *br_stack = ctx->data->br_stack;
1683 	u32 to_copy;
1684 
1685 	if (unlikely(flags & ~BPF_F_GET_BRANCH_RECORDS_SIZE))
1686 		return -EINVAL;
1687 
1688 	if (unlikely(!(ctx->data->sample_flags & PERF_SAMPLE_BRANCH_STACK)))
1689 		return -ENOENT;
1690 
1691 	if (unlikely(!br_stack))
1692 		return -ENOENT;
1693 
1694 	if (flags & BPF_F_GET_BRANCH_RECORDS_SIZE)
1695 		return br_stack->nr * br_entry_size;
1696 
1697 	if (!buf || (size % br_entry_size != 0))
1698 		return -EINVAL;
1699 
1700 	to_copy = min_t(u32, br_stack->nr * br_entry_size, size);
1701 	memcpy(buf, br_stack->entries, to_copy);
1702 
1703 	return to_copy;
1704 }
1705 
1706 static const struct bpf_func_proto bpf_read_branch_records_proto = {
1707 	.func           = bpf_read_branch_records,
1708 	.gpl_only       = true,
1709 	.ret_type       = RET_INTEGER,
1710 	.arg1_type      = ARG_PTR_TO_CTX,
1711 	.arg2_type      = ARG_PTR_TO_MEM_OR_NULL,
1712 	.arg3_type      = ARG_CONST_SIZE_OR_ZERO,
1713 	.arg4_type      = ARG_ANYTHING,
1714 };
1715 
1716 static const struct bpf_func_proto *
pe_prog_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)1717 pe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1718 {
1719 	switch (func_id) {
1720 	case BPF_FUNC_perf_event_output:
1721 		return &bpf_perf_event_output_proto_tp;
1722 	case BPF_FUNC_get_stackid:
1723 		return &bpf_get_stackid_proto_pe;
1724 	case BPF_FUNC_get_stack:
1725 		return &bpf_get_stack_proto_pe;
1726 	case BPF_FUNC_perf_prog_read_value:
1727 		return &bpf_perf_prog_read_value_proto;
1728 	case BPF_FUNC_read_branch_records:
1729 		return &bpf_read_branch_records_proto;
1730 	case BPF_FUNC_get_attach_cookie:
1731 		return &bpf_get_attach_cookie_proto_pe;
1732 	default:
1733 		return bpf_tracing_func_proto(func_id, prog);
1734 	}
1735 }
1736 
1737 /*
1738  * bpf_raw_tp_regs are separate from bpf_pt_regs used from skb/xdp
1739  * to avoid potential recursive reuse issue when/if tracepoints are added
1740  * inside bpf_*_event_output, bpf_get_stackid and/or bpf_get_stack.
1741  *
1742  * Since raw tracepoints run despite bpf_prog_active, support concurrent usage
1743  * in normal, irq, and nmi context.
1744  */
1745 struct bpf_raw_tp_regs {
1746 	struct pt_regs regs[3];
1747 };
1748 static DEFINE_PER_CPU(struct bpf_raw_tp_regs, bpf_raw_tp_regs);
1749 static DEFINE_PER_CPU(int, bpf_raw_tp_nest_level);
get_bpf_raw_tp_regs(void)1750 static struct pt_regs *get_bpf_raw_tp_regs(void)
1751 {
1752 	struct bpf_raw_tp_regs *tp_regs = this_cpu_ptr(&bpf_raw_tp_regs);
1753 	int nest_level = this_cpu_inc_return(bpf_raw_tp_nest_level);
1754 
1755 	if (nest_level > ARRAY_SIZE(tp_regs->regs)) {
1756 		this_cpu_dec(bpf_raw_tp_nest_level);
1757 		return ERR_PTR(-EBUSY);
1758 	}
1759 
1760 	return &tp_regs->regs[nest_level - 1];
1761 }
1762 
put_bpf_raw_tp_regs(void)1763 static void put_bpf_raw_tp_regs(void)
1764 {
1765 	this_cpu_dec(bpf_raw_tp_nest_level);
1766 }
1767 
BPF_CALL_5(bpf_perf_event_output_raw_tp,struct bpf_raw_tracepoint_args *,args,struct bpf_map *,map,u64,flags,void *,data,u64,size)1768 BPF_CALL_5(bpf_perf_event_output_raw_tp, struct bpf_raw_tracepoint_args *, args,
1769 	   struct bpf_map *, map, u64, flags, void *, data, u64, size)
1770 {
1771 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1772 	int ret;
1773 
1774 	if (IS_ERR(regs))
1775 		return PTR_ERR(regs);
1776 
1777 	perf_fetch_caller_regs(regs);
1778 	ret = ____bpf_perf_event_output(regs, map, flags, data, size);
1779 
1780 	put_bpf_raw_tp_regs();
1781 	return ret;
1782 }
1783 
1784 static const struct bpf_func_proto bpf_perf_event_output_proto_raw_tp = {
1785 	.func		= bpf_perf_event_output_raw_tp,
1786 	.gpl_only	= true,
1787 	.ret_type	= RET_INTEGER,
1788 	.arg1_type	= ARG_PTR_TO_CTX,
1789 	.arg2_type	= ARG_CONST_MAP_PTR,
1790 	.arg3_type	= ARG_ANYTHING,
1791 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1792 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
1793 };
1794 
1795 extern const struct bpf_func_proto bpf_skb_output_proto;
1796 extern const struct bpf_func_proto bpf_xdp_output_proto;
1797 extern const struct bpf_func_proto bpf_xdp_get_buff_len_trace_proto;
1798 
BPF_CALL_3(bpf_get_stackid_raw_tp,struct bpf_raw_tracepoint_args *,args,struct bpf_map *,map,u64,flags)1799 BPF_CALL_3(bpf_get_stackid_raw_tp, struct bpf_raw_tracepoint_args *, args,
1800 	   struct bpf_map *, map, u64, flags)
1801 {
1802 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1803 	int ret;
1804 
1805 	if (IS_ERR(regs))
1806 		return PTR_ERR(regs);
1807 
1808 	perf_fetch_caller_regs(regs);
1809 	/* similar to bpf_perf_event_output_tp, but pt_regs fetched differently */
1810 	ret = bpf_get_stackid((unsigned long) regs, (unsigned long) map,
1811 			      flags, 0, 0);
1812 	put_bpf_raw_tp_regs();
1813 	return ret;
1814 }
1815 
1816 static const struct bpf_func_proto bpf_get_stackid_proto_raw_tp = {
1817 	.func		= bpf_get_stackid_raw_tp,
1818 	.gpl_only	= true,
1819 	.ret_type	= RET_INTEGER,
1820 	.arg1_type	= ARG_PTR_TO_CTX,
1821 	.arg2_type	= ARG_CONST_MAP_PTR,
1822 	.arg3_type	= ARG_ANYTHING,
1823 };
1824 
BPF_CALL_4(bpf_get_stack_raw_tp,struct bpf_raw_tracepoint_args *,args,void *,buf,u32,size,u64,flags)1825 BPF_CALL_4(bpf_get_stack_raw_tp, struct bpf_raw_tracepoint_args *, args,
1826 	   void *, buf, u32, size, u64, flags)
1827 {
1828 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1829 	int ret;
1830 
1831 	if (IS_ERR(regs))
1832 		return PTR_ERR(regs);
1833 
1834 	perf_fetch_caller_regs(regs);
1835 	ret = bpf_get_stack((unsigned long) regs, (unsigned long) buf,
1836 			    (unsigned long) size, flags, 0);
1837 	put_bpf_raw_tp_regs();
1838 	return ret;
1839 }
1840 
1841 static const struct bpf_func_proto bpf_get_stack_proto_raw_tp = {
1842 	.func		= bpf_get_stack_raw_tp,
1843 	.gpl_only	= true,
1844 	.ret_type	= RET_INTEGER,
1845 	.arg1_type	= ARG_PTR_TO_CTX,
1846 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1847 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
1848 	.arg4_type	= ARG_ANYTHING,
1849 };
1850 
1851 static const struct bpf_func_proto *
raw_tp_prog_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)1852 raw_tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1853 {
1854 	switch (func_id) {
1855 	case BPF_FUNC_perf_event_output:
1856 		return &bpf_perf_event_output_proto_raw_tp;
1857 	case BPF_FUNC_get_stackid:
1858 		return &bpf_get_stackid_proto_raw_tp;
1859 	case BPF_FUNC_get_stack:
1860 		return &bpf_get_stack_proto_raw_tp;
1861 	case BPF_FUNC_get_attach_cookie:
1862 		return &bpf_get_attach_cookie_proto_tracing;
1863 	default:
1864 		return bpf_tracing_func_proto(func_id, prog);
1865 	}
1866 }
1867 
1868 const struct bpf_func_proto *
tracing_prog_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)1869 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1870 {
1871 	const struct bpf_func_proto *fn;
1872 
1873 	switch (func_id) {
1874 #ifdef CONFIG_NET
1875 	case BPF_FUNC_skb_output:
1876 		return &bpf_skb_output_proto;
1877 	case BPF_FUNC_xdp_output:
1878 		return &bpf_xdp_output_proto;
1879 	case BPF_FUNC_skc_to_tcp6_sock:
1880 		return &bpf_skc_to_tcp6_sock_proto;
1881 	case BPF_FUNC_skc_to_tcp_sock:
1882 		return &bpf_skc_to_tcp_sock_proto;
1883 	case BPF_FUNC_skc_to_tcp_timewait_sock:
1884 		return &bpf_skc_to_tcp_timewait_sock_proto;
1885 	case BPF_FUNC_skc_to_tcp_request_sock:
1886 		return &bpf_skc_to_tcp_request_sock_proto;
1887 	case BPF_FUNC_skc_to_udp6_sock:
1888 		return &bpf_skc_to_udp6_sock_proto;
1889 	case BPF_FUNC_skc_to_unix_sock:
1890 		return &bpf_skc_to_unix_sock_proto;
1891 	case BPF_FUNC_skc_to_mptcp_sock:
1892 		return &bpf_skc_to_mptcp_sock_proto;
1893 	case BPF_FUNC_sk_storage_get:
1894 		return &bpf_sk_storage_get_tracing_proto;
1895 	case BPF_FUNC_sk_storage_delete:
1896 		return &bpf_sk_storage_delete_tracing_proto;
1897 	case BPF_FUNC_sock_from_file:
1898 		return &bpf_sock_from_file_proto;
1899 	case BPF_FUNC_get_socket_cookie:
1900 		return &bpf_get_socket_ptr_cookie_proto;
1901 	case BPF_FUNC_xdp_get_buff_len:
1902 		return &bpf_xdp_get_buff_len_trace_proto;
1903 #endif
1904 	case BPF_FUNC_seq_printf:
1905 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1906 		       &bpf_seq_printf_proto :
1907 		       NULL;
1908 	case BPF_FUNC_seq_write:
1909 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1910 		       &bpf_seq_write_proto :
1911 		       NULL;
1912 	case BPF_FUNC_seq_printf_btf:
1913 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1914 		       &bpf_seq_printf_btf_proto :
1915 		       NULL;
1916 	case BPF_FUNC_d_path:
1917 		return &bpf_d_path_proto;
1918 	case BPF_FUNC_get_func_arg:
1919 		return bpf_prog_has_trampoline(prog) ? &bpf_get_func_arg_proto : NULL;
1920 	case BPF_FUNC_get_func_ret:
1921 		return bpf_prog_has_trampoline(prog) ? &bpf_get_func_ret_proto : NULL;
1922 	case BPF_FUNC_get_func_arg_cnt:
1923 		return bpf_prog_has_trampoline(prog) ? &bpf_get_func_arg_cnt_proto : NULL;
1924 	case BPF_FUNC_get_attach_cookie:
1925 		if (prog->type == BPF_PROG_TYPE_TRACING &&
1926 		    prog->expected_attach_type == BPF_TRACE_RAW_TP)
1927 			return &bpf_get_attach_cookie_proto_tracing;
1928 		return bpf_prog_has_trampoline(prog) ? &bpf_get_attach_cookie_proto_tracing : NULL;
1929 	default:
1930 		fn = raw_tp_prog_func_proto(func_id, prog);
1931 		if (!fn && prog->expected_attach_type == BPF_TRACE_ITER)
1932 			fn = bpf_iter_get_func_proto(func_id, prog);
1933 		return fn;
1934 	}
1935 }
1936 
raw_tp_prog_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)1937 static bool raw_tp_prog_is_valid_access(int off, int size,
1938 					enum bpf_access_type type,
1939 					const struct bpf_prog *prog,
1940 					struct bpf_insn_access_aux *info)
1941 {
1942 	return bpf_tracing_ctx_access(off, size, type);
1943 }
1944 
tracing_prog_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)1945 static bool tracing_prog_is_valid_access(int off, int size,
1946 					 enum bpf_access_type type,
1947 					 const struct bpf_prog *prog,
1948 					 struct bpf_insn_access_aux *info)
1949 {
1950 	return bpf_tracing_btf_ctx_access(off, size, type, prog, info);
1951 }
1952 
bpf_prog_test_run_tracing(struct bpf_prog * prog,const union bpf_attr * kattr,union bpf_attr __user * uattr)1953 int __weak bpf_prog_test_run_tracing(struct bpf_prog *prog,
1954 				     const union bpf_attr *kattr,
1955 				     union bpf_attr __user *uattr)
1956 {
1957 	return -ENOTSUPP;
1958 }
1959 
1960 const struct bpf_verifier_ops raw_tracepoint_verifier_ops = {
1961 	.get_func_proto  = raw_tp_prog_func_proto,
1962 	.is_valid_access = raw_tp_prog_is_valid_access,
1963 };
1964 
1965 const struct bpf_prog_ops raw_tracepoint_prog_ops = {
1966 #ifdef CONFIG_NET
1967 	.test_run = bpf_prog_test_run_raw_tp,
1968 #endif
1969 };
1970 
1971 const struct bpf_verifier_ops tracing_verifier_ops = {
1972 	.get_func_proto  = tracing_prog_func_proto,
1973 	.is_valid_access = tracing_prog_is_valid_access,
1974 };
1975 
1976 const struct bpf_prog_ops tracing_prog_ops = {
1977 	.test_run = bpf_prog_test_run_tracing,
1978 };
1979 
raw_tp_writable_prog_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)1980 static bool raw_tp_writable_prog_is_valid_access(int off, int size,
1981 						 enum bpf_access_type type,
1982 						 const struct bpf_prog *prog,
1983 						 struct bpf_insn_access_aux *info)
1984 {
1985 	if (off == 0) {
1986 		if (size != sizeof(u64) || type != BPF_READ)
1987 			return false;
1988 		info->reg_type = PTR_TO_TP_BUFFER;
1989 	}
1990 	return raw_tp_prog_is_valid_access(off, size, type, prog, info);
1991 }
1992 
1993 const struct bpf_verifier_ops raw_tracepoint_writable_verifier_ops = {
1994 	.get_func_proto  = raw_tp_prog_func_proto,
1995 	.is_valid_access = raw_tp_writable_prog_is_valid_access,
1996 };
1997 
1998 const struct bpf_prog_ops raw_tracepoint_writable_prog_ops = {
1999 };
2000 
pe_prog_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)2001 static bool pe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
2002 				    const struct bpf_prog *prog,
2003 				    struct bpf_insn_access_aux *info)
2004 {
2005 	const int size_u64 = sizeof(u64);
2006 
2007 	if (off < 0 || off >= sizeof(struct bpf_perf_event_data))
2008 		return false;
2009 	if (type != BPF_READ)
2010 		return false;
2011 	if (off % size != 0) {
2012 		if (sizeof(unsigned long) != 4)
2013 			return false;
2014 		if (size != 8)
2015 			return false;
2016 		if (off % size != 4)
2017 			return false;
2018 	}
2019 
2020 	switch (off) {
2021 	case bpf_ctx_range(struct bpf_perf_event_data, sample_period):
2022 		bpf_ctx_record_field_size(info, size_u64);
2023 		if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
2024 			return false;
2025 		break;
2026 	case bpf_ctx_range(struct bpf_perf_event_data, addr):
2027 		bpf_ctx_record_field_size(info, size_u64);
2028 		if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
2029 			return false;
2030 		break;
2031 	default:
2032 		if (size != sizeof(long))
2033 			return false;
2034 	}
2035 
2036 	return true;
2037 }
2038 
pe_prog_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)2039 static u32 pe_prog_convert_ctx_access(enum bpf_access_type type,
2040 				      const struct bpf_insn *si,
2041 				      struct bpf_insn *insn_buf,
2042 				      struct bpf_prog *prog, u32 *target_size)
2043 {
2044 	struct bpf_insn *insn = insn_buf;
2045 
2046 	switch (si->off) {
2047 	case offsetof(struct bpf_perf_event_data, sample_period):
2048 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
2049 						       data), si->dst_reg, si->src_reg,
2050 				      offsetof(struct bpf_perf_event_data_kern, data));
2051 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
2052 				      bpf_target_off(struct perf_sample_data, period, 8,
2053 						     target_size));
2054 		break;
2055 	case offsetof(struct bpf_perf_event_data, addr):
2056 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
2057 						       data), si->dst_reg, si->src_reg,
2058 				      offsetof(struct bpf_perf_event_data_kern, data));
2059 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
2060 				      bpf_target_off(struct perf_sample_data, addr, 8,
2061 						     target_size));
2062 		break;
2063 	default:
2064 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
2065 						       regs), si->dst_reg, si->src_reg,
2066 				      offsetof(struct bpf_perf_event_data_kern, regs));
2067 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(long), si->dst_reg, si->dst_reg,
2068 				      si->off);
2069 		break;
2070 	}
2071 
2072 	return insn - insn_buf;
2073 }
2074 
2075 const struct bpf_verifier_ops perf_event_verifier_ops = {
2076 	.get_func_proto		= pe_prog_func_proto,
2077 	.is_valid_access	= pe_prog_is_valid_access,
2078 	.convert_ctx_access	= pe_prog_convert_ctx_access,
2079 };
2080 
2081 const struct bpf_prog_ops perf_event_prog_ops = {
2082 };
2083 
2084 static DEFINE_MUTEX(bpf_event_mutex);
2085 
2086 #define BPF_TRACE_MAX_PROGS 64
2087 
perf_event_attach_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)2088 int perf_event_attach_bpf_prog(struct perf_event *event,
2089 			       struct bpf_prog *prog,
2090 			       u64 bpf_cookie)
2091 {
2092 	struct bpf_prog_array *old_array;
2093 	struct bpf_prog_array *new_array;
2094 	int ret = -EEXIST;
2095 
2096 	/*
2097 	 * Kprobe override only works if they are on the function entry,
2098 	 * and only if they are on the opt-in list.
2099 	 */
2100 	if (prog->kprobe_override &&
2101 	    (!trace_kprobe_on_func_entry(event->tp_event) ||
2102 	     !trace_kprobe_error_injectable(event->tp_event)))
2103 		return -EINVAL;
2104 
2105 	mutex_lock(&bpf_event_mutex);
2106 
2107 	if (event->prog)
2108 		goto unlock;
2109 
2110 	old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
2111 	if (old_array &&
2112 	    bpf_prog_array_length(old_array) >= BPF_TRACE_MAX_PROGS) {
2113 		ret = -E2BIG;
2114 		goto unlock;
2115 	}
2116 
2117 	ret = bpf_prog_array_copy(old_array, NULL, prog, bpf_cookie, &new_array);
2118 	if (ret < 0)
2119 		goto unlock;
2120 
2121 	/* set the new array to event->tp_event and set event->prog */
2122 	event->prog = prog;
2123 	event->bpf_cookie = bpf_cookie;
2124 	rcu_assign_pointer(event->tp_event->prog_array, new_array);
2125 	bpf_prog_array_free_sleepable(old_array);
2126 
2127 unlock:
2128 	mutex_unlock(&bpf_event_mutex);
2129 	return ret;
2130 }
2131 
perf_event_detach_bpf_prog(struct perf_event * event)2132 void perf_event_detach_bpf_prog(struct perf_event *event)
2133 {
2134 	struct bpf_prog_array *old_array;
2135 	struct bpf_prog_array *new_array;
2136 	struct bpf_prog *prog = NULL;
2137 	int ret;
2138 
2139 	mutex_lock(&bpf_event_mutex);
2140 
2141 	if (!event->prog)
2142 		goto unlock;
2143 
2144 	old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
2145 	if (!old_array)
2146 		goto put;
2147 
2148 	ret = bpf_prog_array_copy(old_array, event->prog, NULL, 0, &new_array);
2149 	if (ret < 0) {
2150 		bpf_prog_array_delete_safe(old_array, event->prog);
2151 	} else {
2152 		rcu_assign_pointer(event->tp_event->prog_array, new_array);
2153 		bpf_prog_array_free_sleepable(old_array);
2154 	}
2155 
2156 put:
2157 	prog = event->prog;
2158 	event->prog = NULL;
2159 
2160 unlock:
2161 	mutex_unlock(&bpf_event_mutex);
2162 
2163 	if (prog) {
2164 		/*
2165 		 * It could be that the bpf_prog is not sleepable (and will be freed
2166 		 * via normal RCU), but is called from a point that supports sleepable
2167 		 * programs and uses tasks-trace-RCU.
2168 		 */
2169 		synchronize_rcu_tasks_trace();
2170 
2171 		bpf_prog_put(prog);
2172 	}
2173 }
2174 
perf_event_query_prog_array(struct perf_event * event,void __user * info)2175 int perf_event_query_prog_array(struct perf_event *event, void __user *info)
2176 {
2177 	struct perf_event_query_bpf __user *uquery = info;
2178 	struct perf_event_query_bpf query = {};
2179 	struct bpf_prog_array *progs;
2180 	u32 *ids, prog_cnt, ids_len;
2181 	int ret;
2182 
2183 	if (!perfmon_capable())
2184 		return -EPERM;
2185 	if (event->attr.type != PERF_TYPE_TRACEPOINT)
2186 		return -EINVAL;
2187 	if (copy_from_user(&query, uquery, sizeof(query)))
2188 		return -EFAULT;
2189 
2190 	ids_len = query.ids_len;
2191 	if (ids_len > BPF_TRACE_MAX_PROGS)
2192 		return -E2BIG;
2193 	ids = kcalloc(ids_len, sizeof(u32), GFP_USER | __GFP_NOWARN);
2194 	if (!ids)
2195 		return -ENOMEM;
2196 	/*
2197 	 * The above kcalloc returns ZERO_SIZE_PTR when ids_len = 0, which
2198 	 * is required when user only wants to check for uquery->prog_cnt.
2199 	 * There is no need to check for it since the case is handled
2200 	 * gracefully in bpf_prog_array_copy_info.
2201 	 */
2202 
2203 	mutex_lock(&bpf_event_mutex);
2204 	progs = bpf_event_rcu_dereference(event->tp_event->prog_array);
2205 	ret = bpf_prog_array_copy_info(progs, ids, ids_len, &prog_cnt);
2206 	mutex_unlock(&bpf_event_mutex);
2207 
2208 	if (copy_to_user(&uquery->prog_cnt, &prog_cnt, sizeof(prog_cnt)) ||
2209 	    copy_to_user(uquery->ids, ids, ids_len * sizeof(u32)))
2210 		ret = -EFAULT;
2211 
2212 	kfree(ids);
2213 	return ret;
2214 }
2215 
2216 extern struct bpf_raw_event_map __start__bpf_raw_tp[];
2217 extern struct bpf_raw_event_map __stop__bpf_raw_tp[];
2218 
bpf_get_raw_tracepoint(const char * name)2219 struct bpf_raw_event_map *bpf_get_raw_tracepoint(const char *name)
2220 {
2221 	struct bpf_raw_event_map *btp = __start__bpf_raw_tp;
2222 
2223 	for (; btp < __stop__bpf_raw_tp; btp++) {
2224 		if (!strcmp(btp->tp->name, name))
2225 			return btp;
2226 	}
2227 
2228 	return bpf_get_raw_tracepoint_module(name);
2229 }
2230 
bpf_put_raw_tracepoint(struct bpf_raw_event_map * btp)2231 void bpf_put_raw_tracepoint(struct bpf_raw_event_map *btp)
2232 {
2233 	struct module *mod;
2234 
2235 	guard(rcu)();
2236 	mod = __module_address((unsigned long)btp);
2237 	module_put(mod);
2238 }
2239 
2240 static __always_inline
__bpf_trace_run(struct bpf_raw_tp_link * link,u64 * args)2241 void __bpf_trace_run(struct bpf_raw_tp_link *link, u64 *args)
2242 {
2243 	struct bpf_prog *prog = link->link.prog;
2244 	struct bpf_run_ctx *old_run_ctx;
2245 	struct bpf_trace_run_ctx run_ctx;
2246 
2247 	cant_sleep();
2248 	if (unlikely(this_cpu_inc_return(*(prog->active)) != 1)) {
2249 		bpf_prog_inc_misses_counter(prog);
2250 		goto out;
2251 	}
2252 
2253 	run_ctx.bpf_cookie = link->cookie;
2254 	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
2255 
2256 	rcu_read_lock();
2257 	(void) bpf_prog_run(prog, args);
2258 	rcu_read_unlock();
2259 
2260 	bpf_reset_run_ctx(old_run_ctx);
2261 out:
2262 	this_cpu_dec(*(prog->active));
2263 }
2264 
2265 #define UNPACK(...)			__VA_ARGS__
2266 #define REPEAT_1(FN, DL, X, ...)	FN(X)
2267 #define REPEAT_2(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_1(FN, DL, __VA_ARGS__)
2268 #define REPEAT_3(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_2(FN, DL, __VA_ARGS__)
2269 #define REPEAT_4(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_3(FN, DL, __VA_ARGS__)
2270 #define REPEAT_5(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_4(FN, DL, __VA_ARGS__)
2271 #define REPEAT_6(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_5(FN, DL, __VA_ARGS__)
2272 #define REPEAT_7(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_6(FN, DL, __VA_ARGS__)
2273 #define REPEAT_8(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_7(FN, DL, __VA_ARGS__)
2274 #define REPEAT_9(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_8(FN, DL, __VA_ARGS__)
2275 #define REPEAT_10(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_9(FN, DL, __VA_ARGS__)
2276 #define REPEAT_11(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_10(FN, DL, __VA_ARGS__)
2277 #define REPEAT_12(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_11(FN, DL, __VA_ARGS__)
2278 #define REPEAT(X, FN, DL, ...)		REPEAT_##X(FN, DL, __VA_ARGS__)
2279 
2280 #define SARG(X)		u64 arg##X
2281 #define COPY(X)		args[X] = arg##X
2282 
2283 #define __DL_COM	(,)
2284 #define __DL_SEM	(;)
2285 
2286 #define __SEQ_0_11	0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
2287 
2288 #define BPF_TRACE_DEFN_x(x)						\
2289 	void bpf_trace_run##x(struct bpf_raw_tp_link *link,		\
2290 			      REPEAT(x, SARG, __DL_COM, __SEQ_0_11))	\
2291 	{								\
2292 		u64 args[x];						\
2293 		REPEAT(x, COPY, __DL_SEM, __SEQ_0_11);			\
2294 		__bpf_trace_run(link, args);				\
2295 	}								\
2296 	EXPORT_SYMBOL_GPL(bpf_trace_run##x)
2297 BPF_TRACE_DEFN_x(1);
2298 BPF_TRACE_DEFN_x(2);
2299 BPF_TRACE_DEFN_x(3);
2300 BPF_TRACE_DEFN_x(4);
2301 BPF_TRACE_DEFN_x(5);
2302 BPF_TRACE_DEFN_x(6);
2303 BPF_TRACE_DEFN_x(7);
2304 BPF_TRACE_DEFN_x(8);
2305 BPF_TRACE_DEFN_x(9);
2306 BPF_TRACE_DEFN_x(10);
2307 BPF_TRACE_DEFN_x(11);
2308 BPF_TRACE_DEFN_x(12);
2309 
bpf_probe_register(struct bpf_raw_event_map * btp,struct bpf_raw_tp_link * link)2310 int bpf_probe_register(struct bpf_raw_event_map *btp, struct bpf_raw_tp_link *link)
2311 {
2312 	struct tracepoint *tp = btp->tp;
2313 	struct bpf_prog *prog = link->link.prog;
2314 
2315 	/*
2316 	 * check that program doesn't access arguments beyond what's
2317 	 * available in this tracepoint
2318 	 */
2319 	if (prog->aux->max_ctx_offset > btp->num_args * sizeof(u64))
2320 		return -EINVAL;
2321 
2322 	if (prog->aux->max_tp_access > btp->writable_size)
2323 		return -EINVAL;
2324 
2325 	return tracepoint_probe_register_may_exist(tp, (void *)btp->bpf_func, link);
2326 }
2327 
bpf_probe_unregister(struct bpf_raw_event_map * btp,struct bpf_raw_tp_link * link)2328 int bpf_probe_unregister(struct bpf_raw_event_map *btp, struct bpf_raw_tp_link *link)
2329 {
2330 	return tracepoint_probe_unregister(btp->tp, (void *)btp->bpf_func, link);
2331 }
2332 
bpf_get_perf_event_info(const struct perf_event * event,u32 * prog_id,u32 * fd_type,const char ** buf,u64 * probe_offset,u64 * probe_addr,unsigned long * missed)2333 int bpf_get_perf_event_info(const struct perf_event *event, u32 *prog_id,
2334 			    u32 *fd_type, const char **buf,
2335 			    u64 *probe_offset, u64 *probe_addr,
2336 			    unsigned long *missed)
2337 {
2338 	bool is_tracepoint, is_syscall_tp;
2339 	struct bpf_prog *prog;
2340 	int flags, err = 0;
2341 
2342 	prog = event->prog;
2343 	if (!prog)
2344 		return -ENOENT;
2345 
2346 	/* not supporting BPF_PROG_TYPE_PERF_EVENT yet */
2347 	if (prog->type == BPF_PROG_TYPE_PERF_EVENT)
2348 		return -EOPNOTSUPP;
2349 
2350 	*prog_id = prog->aux->id;
2351 	flags = event->tp_event->flags;
2352 	is_tracepoint = flags & TRACE_EVENT_FL_TRACEPOINT;
2353 	is_syscall_tp = is_syscall_trace_event(event->tp_event);
2354 
2355 	if (is_tracepoint || is_syscall_tp) {
2356 		*buf = is_tracepoint ? event->tp_event->tp->name
2357 				     : event->tp_event->name;
2358 		/* We allow NULL pointer for tracepoint */
2359 		if (fd_type)
2360 			*fd_type = BPF_FD_TYPE_TRACEPOINT;
2361 		if (probe_offset)
2362 			*probe_offset = 0x0;
2363 		if (probe_addr)
2364 			*probe_addr = 0x0;
2365 	} else {
2366 		/* kprobe/uprobe */
2367 		err = -EOPNOTSUPP;
2368 #ifdef CONFIG_KPROBE_EVENTS
2369 		if (flags & TRACE_EVENT_FL_KPROBE)
2370 			err = bpf_get_kprobe_info(event, fd_type, buf,
2371 						  probe_offset, probe_addr, missed,
2372 						  event->attr.type == PERF_TYPE_TRACEPOINT);
2373 #endif
2374 #ifdef CONFIG_UPROBE_EVENTS
2375 		if (flags & TRACE_EVENT_FL_UPROBE)
2376 			err = bpf_get_uprobe_info(event, fd_type, buf,
2377 						  probe_offset, probe_addr,
2378 						  event->attr.type == PERF_TYPE_TRACEPOINT);
2379 #endif
2380 	}
2381 
2382 	return err;
2383 }
2384 
send_signal_irq_work_init(void)2385 static int __init send_signal_irq_work_init(void)
2386 {
2387 	int cpu;
2388 	struct send_signal_irq_work *work;
2389 
2390 	for_each_possible_cpu(cpu) {
2391 		work = per_cpu_ptr(&send_signal_work, cpu);
2392 		init_irq_work(&work->irq_work, do_bpf_send_signal);
2393 	}
2394 	return 0;
2395 }
2396 
2397 subsys_initcall(send_signal_irq_work_init);
2398 
2399 #ifdef CONFIG_MODULES
bpf_event_notify(struct notifier_block * nb,unsigned long op,void * module)2400 static int bpf_event_notify(struct notifier_block *nb, unsigned long op,
2401 			    void *module)
2402 {
2403 	struct bpf_trace_module *btm, *tmp;
2404 	struct module *mod = module;
2405 	int ret = 0;
2406 
2407 	if (mod->num_bpf_raw_events == 0 ||
2408 	    (op != MODULE_STATE_COMING && op != MODULE_STATE_GOING))
2409 		goto out;
2410 
2411 	mutex_lock(&bpf_module_mutex);
2412 
2413 	switch (op) {
2414 	case MODULE_STATE_COMING:
2415 		btm = kzalloc(sizeof(*btm), GFP_KERNEL);
2416 		if (btm) {
2417 			btm->module = module;
2418 			list_add(&btm->list, &bpf_trace_modules);
2419 		} else {
2420 			ret = -ENOMEM;
2421 		}
2422 		break;
2423 	case MODULE_STATE_GOING:
2424 		list_for_each_entry_safe(btm, tmp, &bpf_trace_modules, list) {
2425 			if (btm->module == module) {
2426 				list_del(&btm->list);
2427 				kfree(btm);
2428 				break;
2429 			}
2430 		}
2431 		break;
2432 	}
2433 
2434 	mutex_unlock(&bpf_module_mutex);
2435 
2436 out:
2437 	return notifier_from_errno(ret);
2438 }
2439 
2440 static struct notifier_block bpf_module_nb = {
2441 	.notifier_call = bpf_event_notify,
2442 };
2443 
bpf_event_init(void)2444 static int __init bpf_event_init(void)
2445 {
2446 	register_module_notifier(&bpf_module_nb);
2447 	return 0;
2448 }
2449 
2450 fs_initcall(bpf_event_init);
2451 #endif /* CONFIG_MODULES */
2452 
2453 struct bpf_session_run_ctx {
2454 	struct bpf_run_ctx run_ctx;
2455 	bool is_return;
2456 	void *data;
2457 };
2458 
2459 #ifdef CONFIG_FPROBE
2460 struct bpf_kprobe_multi_link {
2461 	struct bpf_link link;
2462 	struct fprobe fp;
2463 	unsigned long *addrs;
2464 	u64 *cookies;
2465 	u32 cnt;
2466 	u32 mods_cnt;
2467 	struct module **mods;
2468 };
2469 
2470 struct bpf_kprobe_multi_run_ctx {
2471 	struct bpf_session_run_ctx session_ctx;
2472 	struct bpf_kprobe_multi_link *link;
2473 	unsigned long entry_ip;
2474 };
2475 
2476 struct user_syms {
2477 	const char **syms;
2478 	char *buf;
2479 };
2480 
2481 #ifndef CONFIG_HAVE_FTRACE_REGS_HAVING_PT_REGS
2482 static DEFINE_PER_CPU(struct pt_regs, bpf_kprobe_multi_pt_regs);
2483 #define bpf_kprobe_multi_pt_regs_ptr()	this_cpu_ptr(&bpf_kprobe_multi_pt_regs)
2484 #else
2485 #define bpf_kprobe_multi_pt_regs_ptr()	(NULL)
2486 #endif
2487 
ftrace_get_entry_ip(unsigned long fentry_ip)2488 static unsigned long ftrace_get_entry_ip(unsigned long fentry_ip)
2489 {
2490 	unsigned long ip = ftrace_get_symaddr(fentry_ip);
2491 
2492 	return ip ? : fentry_ip;
2493 }
2494 
copy_user_syms(struct user_syms * us,unsigned long __user * usyms,u32 cnt)2495 static int copy_user_syms(struct user_syms *us, unsigned long __user *usyms, u32 cnt)
2496 {
2497 	unsigned long __user usymbol;
2498 	const char **syms = NULL;
2499 	char *buf = NULL, *p;
2500 	int err = -ENOMEM;
2501 	unsigned int i;
2502 
2503 	syms = kvmalloc_array(cnt, sizeof(*syms), GFP_KERNEL);
2504 	if (!syms)
2505 		goto error;
2506 
2507 	buf = kvmalloc_array(cnt, KSYM_NAME_LEN, GFP_KERNEL);
2508 	if (!buf)
2509 		goto error;
2510 
2511 	for (p = buf, i = 0; i < cnt; i++) {
2512 		if (__get_user(usymbol, usyms + i)) {
2513 			err = -EFAULT;
2514 			goto error;
2515 		}
2516 		err = strncpy_from_user(p, (const char __user *) usymbol, KSYM_NAME_LEN);
2517 		if (err == KSYM_NAME_LEN)
2518 			err = -E2BIG;
2519 		if (err < 0)
2520 			goto error;
2521 		syms[i] = p;
2522 		p += err + 1;
2523 	}
2524 
2525 	us->syms = syms;
2526 	us->buf = buf;
2527 	return 0;
2528 
2529 error:
2530 	if (err) {
2531 		kvfree(syms);
2532 		kvfree(buf);
2533 	}
2534 	return err;
2535 }
2536 
kprobe_multi_put_modules(struct module ** mods,u32 cnt)2537 static void kprobe_multi_put_modules(struct module **mods, u32 cnt)
2538 {
2539 	u32 i;
2540 
2541 	for (i = 0; i < cnt; i++)
2542 		module_put(mods[i]);
2543 }
2544 
free_user_syms(struct user_syms * us)2545 static void free_user_syms(struct user_syms *us)
2546 {
2547 	kvfree(us->syms);
2548 	kvfree(us->buf);
2549 }
2550 
bpf_kprobe_multi_link_release(struct bpf_link * link)2551 static void bpf_kprobe_multi_link_release(struct bpf_link *link)
2552 {
2553 	struct bpf_kprobe_multi_link *kmulti_link;
2554 
2555 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2556 	unregister_fprobe(&kmulti_link->fp);
2557 	kprobe_multi_put_modules(kmulti_link->mods, kmulti_link->mods_cnt);
2558 }
2559 
bpf_kprobe_multi_link_dealloc(struct bpf_link * link)2560 static void bpf_kprobe_multi_link_dealloc(struct bpf_link *link)
2561 {
2562 	struct bpf_kprobe_multi_link *kmulti_link;
2563 
2564 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2565 	kvfree(kmulti_link->addrs);
2566 	kvfree(kmulti_link->cookies);
2567 	kfree(kmulti_link->mods);
2568 	kfree(kmulti_link);
2569 }
2570 
bpf_kprobe_multi_link_fill_link_info(const struct bpf_link * link,struct bpf_link_info * info)2571 static int bpf_kprobe_multi_link_fill_link_info(const struct bpf_link *link,
2572 						struct bpf_link_info *info)
2573 {
2574 	u64 __user *ucookies = u64_to_user_ptr(info->kprobe_multi.cookies);
2575 	u64 __user *uaddrs = u64_to_user_ptr(info->kprobe_multi.addrs);
2576 	struct bpf_kprobe_multi_link *kmulti_link;
2577 	u32 ucount = info->kprobe_multi.count;
2578 	int err = 0, i;
2579 
2580 	if (!uaddrs ^ !ucount)
2581 		return -EINVAL;
2582 	if (ucookies && !ucount)
2583 		return -EINVAL;
2584 
2585 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2586 	info->kprobe_multi.count = kmulti_link->cnt;
2587 	info->kprobe_multi.flags = kmulti_link->link.flags;
2588 	info->kprobe_multi.missed = kmulti_link->fp.nmissed;
2589 
2590 	if (!uaddrs)
2591 		return 0;
2592 	if (ucount < kmulti_link->cnt)
2593 		err = -ENOSPC;
2594 	else
2595 		ucount = kmulti_link->cnt;
2596 
2597 	if (ucookies) {
2598 		if (kmulti_link->cookies) {
2599 			if (copy_to_user(ucookies, kmulti_link->cookies, ucount * sizeof(u64)))
2600 				return -EFAULT;
2601 		} else {
2602 			for (i = 0; i < ucount; i++) {
2603 				if (put_user(0, ucookies + i))
2604 					return -EFAULT;
2605 			}
2606 		}
2607 	}
2608 
2609 	if (kallsyms_show_value(current_cred())) {
2610 		if (copy_to_user(uaddrs, kmulti_link->addrs, ucount * sizeof(u64)))
2611 			return -EFAULT;
2612 	} else {
2613 		for (i = 0; i < ucount; i++) {
2614 			if (put_user(0, uaddrs + i))
2615 				return -EFAULT;
2616 		}
2617 	}
2618 	return err;
2619 }
2620 
2621 #ifdef CONFIG_PROC_FS
bpf_kprobe_multi_show_fdinfo(const struct bpf_link * link,struct seq_file * seq)2622 static void bpf_kprobe_multi_show_fdinfo(const struct bpf_link *link,
2623 					 struct seq_file *seq)
2624 {
2625 	struct bpf_kprobe_multi_link *kmulti_link;
2626 
2627 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2628 
2629 	seq_printf(seq,
2630 		   "kprobe_cnt:\t%u\n"
2631 		   "missed:\t%lu\n",
2632 		   kmulti_link->cnt,
2633 		   kmulti_link->fp.nmissed);
2634 
2635 	seq_printf(seq, "%s\t %s\n", "cookie", "func");
2636 	for (int i = 0; i < kmulti_link->cnt; i++) {
2637 		seq_printf(seq,
2638 			   "%llu\t %pS\n",
2639 			   kmulti_link->cookies[i],
2640 			   (void *)kmulti_link->addrs[i]);
2641 	}
2642 }
2643 #endif
2644 
2645 static const struct bpf_link_ops bpf_kprobe_multi_link_lops = {
2646 	.release = bpf_kprobe_multi_link_release,
2647 	.dealloc_deferred = bpf_kprobe_multi_link_dealloc,
2648 	.fill_link_info = bpf_kprobe_multi_link_fill_link_info,
2649 #ifdef CONFIG_PROC_FS
2650 	.show_fdinfo = bpf_kprobe_multi_show_fdinfo,
2651 #endif
2652 };
2653 
bpf_kprobe_multi_cookie_swap(void * a,void * b,int size,const void * priv)2654 static void bpf_kprobe_multi_cookie_swap(void *a, void *b, int size, const void *priv)
2655 {
2656 	const struct bpf_kprobe_multi_link *link = priv;
2657 	unsigned long *addr_a = a, *addr_b = b;
2658 	u64 *cookie_a, *cookie_b;
2659 
2660 	cookie_a = link->cookies + (addr_a - link->addrs);
2661 	cookie_b = link->cookies + (addr_b - link->addrs);
2662 
2663 	/* swap addr_a/addr_b and cookie_a/cookie_b values */
2664 	swap(*addr_a, *addr_b);
2665 	swap(*cookie_a, *cookie_b);
2666 }
2667 
bpf_kprobe_multi_addrs_cmp(const void * a,const void * b)2668 static int bpf_kprobe_multi_addrs_cmp(const void *a, const void *b)
2669 {
2670 	const unsigned long *addr_a = a, *addr_b = b;
2671 
2672 	if (*addr_a == *addr_b)
2673 		return 0;
2674 	return *addr_a < *addr_b ? -1 : 1;
2675 }
2676 
bpf_kprobe_multi_cookie_cmp(const void * a,const void * b,const void * priv)2677 static int bpf_kprobe_multi_cookie_cmp(const void *a, const void *b, const void *priv)
2678 {
2679 	return bpf_kprobe_multi_addrs_cmp(a, b);
2680 }
2681 
bpf_kprobe_multi_cookie(struct bpf_run_ctx * ctx)2682 static u64 bpf_kprobe_multi_cookie(struct bpf_run_ctx *ctx)
2683 {
2684 	struct bpf_kprobe_multi_run_ctx *run_ctx;
2685 	struct bpf_kprobe_multi_link *link;
2686 	u64 *cookie, entry_ip;
2687 	unsigned long *addr;
2688 
2689 	if (WARN_ON_ONCE(!ctx))
2690 		return 0;
2691 	run_ctx = container_of(current->bpf_ctx, struct bpf_kprobe_multi_run_ctx,
2692 			       session_ctx.run_ctx);
2693 	link = run_ctx->link;
2694 	if (!link->cookies)
2695 		return 0;
2696 	entry_ip = run_ctx->entry_ip;
2697 	addr = bsearch(&entry_ip, link->addrs, link->cnt, sizeof(entry_ip),
2698 		       bpf_kprobe_multi_addrs_cmp);
2699 	if (!addr)
2700 		return 0;
2701 	cookie = link->cookies + (addr - link->addrs);
2702 	return *cookie;
2703 }
2704 
bpf_kprobe_multi_entry_ip(struct bpf_run_ctx * ctx)2705 static u64 bpf_kprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
2706 {
2707 	struct bpf_kprobe_multi_run_ctx *run_ctx;
2708 
2709 	run_ctx = container_of(current->bpf_ctx, struct bpf_kprobe_multi_run_ctx,
2710 			       session_ctx.run_ctx);
2711 	return run_ctx->entry_ip;
2712 }
2713 
2714 static int
kprobe_multi_link_prog_run(struct bpf_kprobe_multi_link * link,unsigned long entry_ip,struct ftrace_regs * fregs,bool is_return,void * data)2715 kprobe_multi_link_prog_run(struct bpf_kprobe_multi_link *link,
2716 			   unsigned long entry_ip, struct ftrace_regs *fregs,
2717 			   bool is_return, void *data)
2718 {
2719 	struct bpf_kprobe_multi_run_ctx run_ctx = {
2720 		.session_ctx = {
2721 			.is_return = is_return,
2722 			.data = data,
2723 		},
2724 		.link = link,
2725 		.entry_ip = entry_ip,
2726 	};
2727 	struct bpf_run_ctx *old_run_ctx;
2728 	struct pt_regs *regs;
2729 	int err;
2730 
2731 	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) {
2732 		bpf_prog_inc_misses_counter(link->link.prog);
2733 		err = 1;
2734 		goto out;
2735 	}
2736 
2737 	migrate_disable();
2738 	rcu_read_lock();
2739 	regs = ftrace_partial_regs(fregs, bpf_kprobe_multi_pt_regs_ptr());
2740 	old_run_ctx = bpf_set_run_ctx(&run_ctx.session_ctx.run_ctx);
2741 	err = bpf_prog_run(link->link.prog, regs);
2742 	bpf_reset_run_ctx(old_run_ctx);
2743 	rcu_read_unlock();
2744 	migrate_enable();
2745 
2746  out:
2747 	__this_cpu_dec(bpf_prog_active);
2748 	return err;
2749 }
2750 
2751 static int
kprobe_multi_link_handler(struct fprobe * fp,unsigned long fentry_ip,unsigned long ret_ip,struct ftrace_regs * fregs,void * data)2752 kprobe_multi_link_handler(struct fprobe *fp, unsigned long fentry_ip,
2753 			  unsigned long ret_ip, struct ftrace_regs *fregs,
2754 			  void *data)
2755 {
2756 	struct bpf_kprobe_multi_link *link;
2757 	int err;
2758 
2759 	link = container_of(fp, struct bpf_kprobe_multi_link, fp);
2760 	err = kprobe_multi_link_prog_run(link, ftrace_get_entry_ip(fentry_ip),
2761 					 fregs, false, data);
2762 	return is_kprobe_session(link->link.prog) ? err : 0;
2763 }
2764 
2765 static void
kprobe_multi_link_exit_handler(struct fprobe * fp,unsigned long fentry_ip,unsigned long ret_ip,struct ftrace_regs * fregs,void * data)2766 kprobe_multi_link_exit_handler(struct fprobe *fp, unsigned long fentry_ip,
2767 			       unsigned long ret_ip, struct ftrace_regs *fregs,
2768 			       void *data)
2769 {
2770 	struct bpf_kprobe_multi_link *link;
2771 
2772 	link = container_of(fp, struct bpf_kprobe_multi_link, fp);
2773 	kprobe_multi_link_prog_run(link, ftrace_get_entry_ip(fentry_ip),
2774 				   fregs, true, data);
2775 }
2776 
symbols_cmp_r(const void * a,const void * b,const void * priv)2777 static int symbols_cmp_r(const void *a, const void *b, const void *priv)
2778 {
2779 	const char **str_a = (const char **) a;
2780 	const char **str_b = (const char **) b;
2781 
2782 	return strcmp(*str_a, *str_b);
2783 }
2784 
2785 struct multi_symbols_sort {
2786 	const char **funcs;
2787 	u64 *cookies;
2788 };
2789 
symbols_swap_r(void * a,void * b,int size,const void * priv)2790 static void symbols_swap_r(void *a, void *b, int size, const void *priv)
2791 {
2792 	const struct multi_symbols_sort *data = priv;
2793 	const char **name_a = a, **name_b = b;
2794 
2795 	swap(*name_a, *name_b);
2796 
2797 	/* If defined, swap also related cookies. */
2798 	if (data->cookies) {
2799 		u64 *cookie_a, *cookie_b;
2800 
2801 		cookie_a = data->cookies + (name_a - data->funcs);
2802 		cookie_b = data->cookies + (name_b - data->funcs);
2803 		swap(*cookie_a, *cookie_b);
2804 	}
2805 }
2806 
2807 struct modules_array {
2808 	struct module **mods;
2809 	int mods_cnt;
2810 	int mods_cap;
2811 };
2812 
add_module(struct modules_array * arr,struct module * mod)2813 static int add_module(struct modules_array *arr, struct module *mod)
2814 {
2815 	struct module **mods;
2816 
2817 	if (arr->mods_cnt == arr->mods_cap) {
2818 		arr->mods_cap = max(16, arr->mods_cap * 3 / 2);
2819 		mods = krealloc_array(arr->mods, arr->mods_cap, sizeof(*mods), GFP_KERNEL);
2820 		if (!mods)
2821 			return -ENOMEM;
2822 		arr->mods = mods;
2823 	}
2824 
2825 	arr->mods[arr->mods_cnt] = mod;
2826 	arr->mods_cnt++;
2827 	return 0;
2828 }
2829 
has_module(struct modules_array * arr,struct module * mod)2830 static bool has_module(struct modules_array *arr, struct module *mod)
2831 {
2832 	int i;
2833 
2834 	for (i = arr->mods_cnt - 1; i >= 0; i--) {
2835 		if (arr->mods[i] == mod)
2836 			return true;
2837 	}
2838 	return false;
2839 }
2840 
get_modules_for_addrs(struct module *** mods,unsigned long * addrs,u32 addrs_cnt)2841 static int get_modules_for_addrs(struct module ***mods, unsigned long *addrs, u32 addrs_cnt)
2842 {
2843 	struct modules_array arr = {};
2844 	u32 i, err = 0;
2845 
2846 	for (i = 0; i < addrs_cnt; i++) {
2847 		bool skip_add = false;
2848 		struct module *mod;
2849 
2850 		scoped_guard(rcu) {
2851 			mod = __module_address(addrs[i]);
2852 			/* Either no module or it's already stored  */
2853 			if (!mod || has_module(&arr, mod)) {
2854 				skip_add = true;
2855 				break; /* scoped_guard */
2856 			}
2857 			if (!try_module_get(mod))
2858 				err = -EINVAL;
2859 		}
2860 		if (skip_add)
2861 			continue;
2862 		if (err)
2863 			break;
2864 		err = add_module(&arr, mod);
2865 		if (err) {
2866 			module_put(mod);
2867 			break;
2868 		}
2869 	}
2870 
2871 	/* We return either err < 0 in case of error, ... */
2872 	if (err) {
2873 		kprobe_multi_put_modules(arr.mods, arr.mods_cnt);
2874 		kfree(arr.mods);
2875 		return err;
2876 	}
2877 
2878 	/* or number of modules found if everything is ok. */
2879 	*mods = arr.mods;
2880 	return arr.mods_cnt;
2881 }
2882 
addrs_check_error_injection_list(unsigned long * addrs,u32 cnt)2883 static int addrs_check_error_injection_list(unsigned long *addrs, u32 cnt)
2884 {
2885 	u32 i;
2886 
2887 	for (i = 0; i < cnt; i++) {
2888 		if (!within_error_injection_list(addrs[i]))
2889 			return -EINVAL;
2890 	}
2891 	return 0;
2892 }
2893 
bpf_kprobe_multi_link_attach(const union bpf_attr * attr,struct bpf_prog * prog)2894 int bpf_kprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
2895 {
2896 	struct bpf_kprobe_multi_link *link = NULL;
2897 	struct bpf_link_primer link_primer;
2898 	void __user *ucookies;
2899 	unsigned long *addrs;
2900 	u32 flags, cnt, size;
2901 	void __user *uaddrs;
2902 	u64 *cookies = NULL;
2903 	void __user *usyms;
2904 	int err;
2905 
2906 	/* no support for 32bit archs yet */
2907 	if (sizeof(u64) != sizeof(void *))
2908 		return -EOPNOTSUPP;
2909 
2910 	if (attr->link_create.flags)
2911 		return -EINVAL;
2912 
2913 	if (!is_kprobe_multi(prog))
2914 		return -EINVAL;
2915 
2916 	flags = attr->link_create.kprobe_multi.flags;
2917 	if (flags & ~BPF_F_KPROBE_MULTI_RETURN)
2918 		return -EINVAL;
2919 
2920 	uaddrs = u64_to_user_ptr(attr->link_create.kprobe_multi.addrs);
2921 	usyms = u64_to_user_ptr(attr->link_create.kprobe_multi.syms);
2922 	if (!!uaddrs == !!usyms)
2923 		return -EINVAL;
2924 
2925 	cnt = attr->link_create.kprobe_multi.cnt;
2926 	if (!cnt)
2927 		return -EINVAL;
2928 	if (cnt > MAX_KPROBE_MULTI_CNT)
2929 		return -E2BIG;
2930 
2931 	size = cnt * sizeof(*addrs);
2932 	addrs = kvmalloc_array(cnt, sizeof(*addrs), GFP_KERNEL);
2933 	if (!addrs)
2934 		return -ENOMEM;
2935 
2936 	ucookies = u64_to_user_ptr(attr->link_create.kprobe_multi.cookies);
2937 	if (ucookies) {
2938 		cookies = kvmalloc_array(cnt, sizeof(*addrs), GFP_KERNEL);
2939 		if (!cookies) {
2940 			err = -ENOMEM;
2941 			goto error;
2942 		}
2943 		if (copy_from_user(cookies, ucookies, size)) {
2944 			err = -EFAULT;
2945 			goto error;
2946 		}
2947 	}
2948 
2949 	if (uaddrs) {
2950 		if (copy_from_user(addrs, uaddrs, size)) {
2951 			err = -EFAULT;
2952 			goto error;
2953 		}
2954 	} else {
2955 		struct multi_symbols_sort data = {
2956 			.cookies = cookies,
2957 		};
2958 		struct user_syms us;
2959 
2960 		err = copy_user_syms(&us, usyms, cnt);
2961 		if (err)
2962 			goto error;
2963 
2964 		if (cookies)
2965 			data.funcs = us.syms;
2966 
2967 		sort_r(us.syms, cnt, sizeof(*us.syms), symbols_cmp_r,
2968 		       symbols_swap_r, &data);
2969 
2970 		err = ftrace_lookup_symbols(us.syms, cnt, addrs);
2971 		free_user_syms(&us);
2972 		if (err)
2973 			goto error;
2974 	}
2975 
2976 	if (prog->kprobe_override && addrs_check_error_injection_list(addrs, cnt)) {
2977 		err = -EINVAL;
2978 		goto error;
2979 	}
2980 
2981 	link = kzalloc(sizeof(*link), GFP_KERNEL);
2982 	if (!link) {
2983 		err = -ENOMEM;
2984 		goto error;
2985 	}
2986 
2987 	bpf_link_init(&link->link, BPF_LINK_TYPE_KPROBE_MULTI,
2988 		      &bpf_kprobe_multi_link_lops, prog, attr->link_create.attach_type);
2989 
2990 	err = bpf_link_prime(&link->link, &link_primer);
2991 	if (err)
2992 		goto error;
2993 
2994 	if (!(flags & BPF_F_KPROBE_MULTI_RETURN))
2995 		link->fp.entry_handler = kprobe_multi_link_handler;
2996 	if ((flags & BPF_F_KPROBE_MULTI_RETURN) || is_kprobe_session(prog))
2997 		link->fp.exit_handler = kprobe_multi_link_exit_handler;
2998 	if (is_kprobe_session(prog))
2999 		link->fp.entry_data_size = sizeof(u64);
3000 
3001 	link->addrs = addrs;
3002 	link->cookies = cookies;
3003 	link->cnt = cnt;
3004 	link->link.flags = flags;
3005 
3006 	if (cookies) {
3007 		/*
3008 		 * Sorting addresses will trigger sorting cookies as well
3009 		 * (check bpf_kprobe_multi_cookie_swap). This way we can
3010 		 * find cookie based on the address in bpf_get_attach_cookie
3011 		 * helper.
3012 		 */
3013 		sort_r(addrs, cnt, sizeof(*addrs),
3014 		       bpf_kprobe_multi_cookie_cmp,
3015 		       bpf_kprobe_multi_cookie_swap,
3016 		       link);
3017 	}
3018 
3019 	err = get_modules_for_addrs(&link->mods, addrs, cnt);
3020 	if (err < 0) {
3021 		bpf_link_cleanup(&link_primer);
3022 		return err;
3023 	}
3024 	link->mods_cnt = err;
3025 
3026 	err = register_fprobe_ips(&link->fp, addrs, cnt);
3027 	if (err) {
3028 		kprobe_multi_put_modules(link->mods, link->mods_cnt);
3029 		bpf_link_cleanup(&link_primer);
3030 		return err;
3031 	}
3032 
3033 	return bpf_link_settle(&link_primer);
3034 
3035 error:
3036 	kfree(link);
3037 	kvfree(addrs);
3038 	kvfree(cookies);
3039 	return err;
3040 }
3041 #else /* !CONFIG_FPROBE */
bpf_kprobe_multi_link_attach(const union bpf_attr * attr,struct bpf_prog * prog)3042 int bpf_kprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3043 {
3044 	return -EOPNOTSUPP;
3045 }
bpf_kprobe_multi_cookie(struct bpf_run_ctx * ctx)3046 static u64 bpf_kprobe_multi_cookie(struct bpf_run_ctx *ctx)
3047 {
3048 	return 0;
3049 }
bpf_kprobe_multi_entry_ip(struct bpf_run_ctx * ctx)3050 static u64 bpf_kprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
3051 {
3052 	return 0;
3053 }
3054 #endif
3055 
3056 #ifdef CONFIG_UPROBES
3057 struct bpf_uprobe_multi_link;
3058 
3059 struct bpf_uprobe {
3060 	struct bpf_uprobe_multi_link *link;
3061 	loff_t offset;
3062 	unsigned long ref_ctr_offset;
3063 	u64 cookie;
3064 	struct uprobe *uprobe;
3065 	struct uprobe_consumer consumer;
3066 	bool session;
3067 };
3068 
3069 struct bpf_uprobe_multi_link {
3070 	struct path path;
3071 	struct bpf_link link;
3072 	u32 cnt;
3073 	struct bpf_uprobe *uprobes;
3074 	struct task_struct *task;
3075 };
3076 
3077 struct bpf_uprobe_multi_run_ctx {
3078 	struct bpf_session_run_ctx session_ctx;
3079 	unsigned long entry_ip;
3080 	struct bpf_uprobe *uprobe;
3081 };
3082 
bpf_uprobe_unregister(struct bpf_uprobe * uprobes,u32 cnt)3083 static void bpf_uprobe_unregister(struct bpf_uprobe *uprobes, u32 cnt)
3084 {
3085 	u32 i;
3086 
3087 	for (i = 0; i < cnt; i++)
3088 		uprobe_unregister_nosync(uprobes[i].uprobe, &uprobes[i].consumer);
3089 
3090 	if (cnt)
3091 		uprobe_unregister_sync();
3092 }
3093 
bpf_uprobe_multi_link_release(struct bpf_link * link)3094 static void bpf_uprobe_multi_link_release(struct bpf_link *link)
3095 {
3096 	struct bpf_uprobe_multi_link *umulti_link;
3097 
3098 	umulti_link = container_of(link, struct bpf_uprobe_multi_link, link);
3099 	bpf_uprobe_unregister(umulti_link->uprobes, umulti_link->cnt);
3100 	if (umulti_link->task)
3101 		put_task_struct(umulti_link->task);
3102 	path_put(&umulti_link->path);
3103 }
3104 
bpf_uprobe_multi_link_dealloc(struct bpf_link * link)3105 static void bpf_uprobe_multi_link_dealloc(struct bpf_link *link)
3106 {
3107 	struct bpf_uprobe_multi_link *umulti_link;
3108 
3109 	umulti_link = container_of(link, struct bpf_uprobe_multi_link, link);
3110 	kvfree(umulti_link->uprobes);
3111 	kfree(umulti_link);
3112 }
3113 
bpf_uprobe_multi_link_fill_link_info(const struct bpf_link * link,struct bpf_link_info * info)3114 static int bpf_uprobe_multi_link_fill_link_info(const struct bpf_link *link,
3115 						struct bpf_link_info *info)
3116 {
3117 	u64 __user *uref_ctr_offsets = u64_to_user_ptr(info->uprobe_multi.ref_ctr_offsets);
3118 	u64 __user *ucookies = u64_to_user_ptr(info->uprobe_multi.cookies);
3119 	u64 __user *uoffsets = u64_to_user_ptr(info->uprobe_multi.offsets);
3120 	u64 __user *upath = u64_to_user_ptr(info->uprobe_multi.path);
3121 	u32 upath_size = info->uprobe_multi.path_size;
3122 	struct bpf_uprobe_multi_link *umulti_link;
3123 	u32 ucount = info->uprobe_multi.count;
3124 	int err = 0, i;
3125 	char *p, *buf;
3126 	long left = 0;
3127 
3128 	if (!upath ^ !upath_size)
3129 		return -EINVAL;
3130 
3131 	if ((uoffsets || uref_ctr_offsets || ucookies) && !ucount)
3132 		return -EINVAL;
3133 
3134 	umulti_link = container_of(link, struct bpf_uprobe_multi_link, link);
3135 	info->uprobe_multi.count = umulti_link->cnt;
3136 	info->uprobe_multi.flags = umulti_link->link.flags;
3137 	info->uprobe_multi.pid = umulti_link->task ?
3138 				 task_pid_nr_ns(umulti_link->task, task_active_pid_ns(current)) : 0;
3139 
3140 	upath_size = upath_size ? min_t(u32, upath_size, PATH_MAX) : PATH_MAX;
3141 	buf = kmalloc(upath_size, GFP_KERNEL);
3142 	if (!buf)
3143 		return -ENOMEM;
3144 	p = d_path(&umulti_link->path, buf, upath_size);
3145 	if (IS_ERR(p)) {
3146 		kfree(buf);
3147 		return PTR_ERR(p);
3148 	}
3149 	upath_size = buf + upath_size - p;
3150 
3151 	if (upath)
3152 		left = copy_to_user(upath, p, upath_size);
3153 	kfree(buf);
3154 	if (left)
3155 		return -EFAULT;
3156 	info->uprobe_multi.path_size = upath_size;
3157 
3158 	if (!uoffsets && !ucookies && !uref_ctr_offsets)
3159 		return 0;
3160 
3161 	if (ucount < umulti_link->cnt)
3162 		err = -ENOSPC;
3163 	else
3164 		ucount = umulti_link->cnt;
3165 
3166 	for (i = 0; i < ucount; i++) {
3167 		if (uoffsets &&
3168 		    put_user(umulti_link->uprobes[i].offset, uoffsets + i))
3169 			return -EFAULT;
3170 		if (uref_ctr_offsets &&
3171 		    put_user(umulti_link->uprobes[i].ref_ctr_offset, uref_ctr_offsets + i))
3172 			return -EFAULT;
3173 		if (ucookies &&
3174 		    put_user(umulti_link->uprobes[i].cookie, ucookies + i))
3175 			return -EFAULT;
3176 	}
3177 
3178 	return err;
3179 }
3180 
3181 #ifdef CONFIG_PROC_FS
bpf_uprobe_multi_show_fdinfo(const struct bpf_link * link,struct seq_file * seq)3182 static void bpf_uprobe_multi_show_fdinfo(const struct bpf_link *link,
3183 					 struct seq_file *seq)
3184 {
3185 	struct bpf_uprobe_multi_link *umulti_link;
3186 	char *p, *buf;
3187 	pid_t pid;
3188 
3189 	umulti_link = container_of(link, struct bpf_uprobe_multi_link, link);
3190 
3191 	buf = kmalloc(PATH_MAX, GFP_KERNEL);
3192 	if (!buf)
3193 		return;
3194 
3195 	p = d_path(&umulti_link->path, buf, PATH_MAX);
3196 	if (IS_ERR(p)) {
3197 		kfree(buf);
3198 		return;
3199 	}
3200 
3201 	pid = umulti_link->task ?
3202 	      task_pid_nr_ns(umulti_link->task, task_active_pid_ns(current)) : 0;
3203 	seq_printf(seq,
3204 		   "uprobe_cnt:\t%u\n"
3205 		   "pid:\t%u\n"
3206 		   "path:\t%s\n",
3207 		   umulti_link->cnt, pid, p);
3208 
3209 	seq_printf(seq, "%s\t %s\t %s\n", "cookie", "offset", "ref_ctr_offset");
3210 	for (int i = 0; i < umulti_link->cnt; i++) {
3211 		seq_printf(seq,
3212 			   "%llu\t %#llx\t %#lx\n",
3213 			   umulti_link->uprobes[i].cookie,
3214 			   umulti_link->uprobes[i].offset,
3215 			   umulti_link->uprobes[i].ref_ctr_offset);
3216 	}
3217 
3218 	kfree(buf);
3219 }
3220 #endif
3221 
3222 static const struct bpf_link_ops bpf_uprobe_multi_link_lops = {
3223 	.release = bpf_uprobe_multi_link_release,
3224 	.dealloc_deferred = bpf_uprobe_multi_link_dealloc,
3225 	.fill_link_info = bpf_uprobe_multi_link_fill_link_info,
3226 #ifdef CONFIG_PROC_FS
3227 	.show_fdinfo = bpf_uprobe_multi_show_fdinfo,
3228 #endif
3229 };
3230 
uprobe_prog_run(struct bpf_uprobe * uprobe,unsigned long entry_ip,struct pt_regs * regs,bool is_return,void * data)3231 static int uprobe_prog_run(struct bpf_uprobe *uprobe,
3232 			   unsigned long entry_ip,
3233 			   struct pt_regs *regs,
3234 			   bool is_return, void *data)
3235 {
3236 	struct bpf_uprobe_multi_link *link = uprobe->link;
3237 	struct bpf_uprobe_multi_run_ctx run_ctx = {
3238 		.session_ctx = {
3239 			.is_return = is_return,
3240 			.data = data,
3241 		},
3242 		.entry_ip = entry_ip,
3243 		.uprobe = uprobe,
3244 	};
3245 	struct bpf_prog *prog = link->link.prog;
3246 	bool sleepable = prog->sleepable;
3247 	struct bpf_run_ctx *old_run_ctx;
3248 	int err;
3249 
3250 	if (link->task && !same_thread_group(current, link->task))
3251 		return 0;
3252 
3253 	if (sleepable)
3254 		rcu_read_lock_trace();
3255 	else
3256 		rcu_read_lock();
3257 
3258 	migrate_disable();
3259 
3260 	old_run_ctx = bpf_set_run_ctx(&run_ctx.session_ctx.run_ctx);
3261 	err = bpf_prog_run(link->link.prog, regs);
3262 	bpf_reset_run_ctx(old_run_ctx);
3263 
3264 	migrate_enable();
3265 
3266 	if (sleepable)
3267 		rcu_read_unlock_trace();
3268 	else
3269 		rcu_read_unlock();
3270 	return err;
3271 }
3272 
3273 static bool
uprobe_multi_link_filter(struct uprobe_consumer * con,struct mm_struct * mm)3274 uprobe_multi_link_filter(struct uprobe_consumer *con, struct mm_struct *mm)
3275 {
3276 	struct bpf_uprobe *uprobe;
3277 
3278 	uprobe = container_of(con, struct bpf_uprobe, consumer);
3279 	return uprobe->link->task->mm == mm;
3280 }
3281 
3282 static int
uprobe_multi_link_handler(struct uprobe_consumer * con,struct pt_regs * regs,__u64 * data)3283 uprobe_multi_link_handler(struct uprobe_consumer *con, struct pt_regs *regs,
3284 			  __u64 *data)
3285 {
3286 	struct bpf_uprobe *uprobe;
3287 	int ret;
3288 
3289 	uprobe = container_of(con, struct bpf_uprobe, consumer);
3290 	ret = uprobe_prog_run(uprobe, instruction_pointer(regs), regs, false, data);
3291 	if (uprobe->session)
3292 		return ret ? UPROBE_HANDLER_IGNORE : 0;
3293 	return 0;
3294 }
3295 
3296 static int
uprobe_multi_link_ret_handler(struct uprobe_consumer * con,unsigned long func,struct pt_regs * regs,__u64 * data)3297 uprobe_multi_link_ret_handler(struct uprobe_consumer *con, unsigned long func, struct pt_regs *regs,
3298 			      __u64 *data)
3299 {
3300 	struct bpf_uprobe *uprobe;
3301 
3302 	uprobe = container_of(con, struct bpf_uprobe, consumer);
3303 	uprobe_prog_run(uprobe, func, regs, true, data);
3304 	return 0;
3305 }
3306 
bpf_uprobe_multi_entry_ip(struct bpf_run_ctx * ctx)3307 static u64 bpf_uprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
3308 {
3309 	struct bpf_uprobe_multi_run_ctx *run_ctx;
3310 
3311 	run_ctx = container_of(current->bpf_ctx, struct bpf_uprobe_multi_run_ctx,
3312 			       session_ctx.run_ctx);
3313 	return run_ctx->entry_ip;
3314 }
3315 
bpf_uprobe_multi_cookie(struct bpf_run_ctx * ctx)3316 static u64 bpf_uprobe_multi_cookie(struct bpf_run_ctx *ctx)
3317 {
3318 	struct bpf_uprobe_multi_run_ctx *run_ctx;
3319 
3320 	run_ctx = container_of(current->bpf_ctx, struct bpf_uprobe_multi_run_ctx,
3321 			       session_ctx.run_ctx);
3322 	return run_ctx->uprobe->cookie;
3323 }
3324 
bpf_uprobe_multi_link_attach(const union bpf_attr * attr,struct bpf_prog * prog)3325 int bpf_uprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3326 {
3327 	struct bpf_uprobe_multi_link *link = NULL;
3328 	unsigned long __user *uref_ctr_offsets;
3329 	struct bpf_link_primer link_primer;
3330 	struct bpf_uprobe *uprobes = NULL;
3331 	struct task_struct *task = NULL;
3332 	unsigned long __user *uoffsets;
3333 	u64 __user *ucookies;
3334 	void __user *upath;
3335 	u32 flags, cnt, i;
3336 	struct path path;
3337 	char *name;
3338 	pid_t pid;
3339 	int err;
3340 
3341 	/* no support for 32bit archs yet */
3342 	if (sizeof(u64) != sizeof(void *))
3343 		return -EOPNOTSUPP;
3344 
3345 	if (attr->link_create.flags)
3346 		return -EINVAL;
3347 
3348 	if (!is_uprobe_multi(prog))
3349 		return -EINVAL;
3350 
3351 	flags = attr->link_create.uprobe_multi.flags;
3352 	if (flags & ~BPF_F_UPROBE_MULTI_RETURN)
3353 		return -EINVAL;
3354 
3355 	/*
3356 	 * path, offsets and cnt are mandatory,
3357 	 * ref_ctr_offsets and cookies are optional
3358 	 */
3359 	upath = u64_to_user_ptr(attr->link_create.uprobe_multi.path);
3360 	uoffsets = u64_to_user_ptr(attr->link_create.uprobe_multi.offsets);
3361 	cnt = attr->link_create.uprobe_multi.cnt;
3362 	pid = attr->link_create.uprobe_multi.pid;
3363 
3364 	if (!upath || !uoffsets || !cnt || pid < 0)
3365 		return -EINVAL;
3366 	if (cnt > MAX_UPROBE_MULTI_CNT)
3367 		return -E2BIG;
3368 
3369 	uref_ctr_offsets = u64_to_user_ptr(attr->link_create.uprobe_multi.ref_ctr_offsets);
3370 	ucookies = u64_to_user_ptr(attr->link_create.uprobe_multi.cookies);
3371 
3372 	name = strndup_user(upath, PATH_MAX);
3373 	if (IS_ERR(name)) {
3374 		err = PTR_ERR(name);
3375 		return err;
3376 	}
3377 
3378 	err = kern_path(name, LOOKUP_FOLLOW, &path);
3379 	kfree(name);
3380 	if (err)
3381 		return err;
3382 
3383 	if (!d_is_reg(path.dentry)) {
3384 		err = -EBADF;
3385 		goto error_path_put;
3386 	}
3387 
3388 	if (pid) {
3389 		rcu_read_lock();
3390 		task = get_pid_task(find_vpid(pid), PIDTYPE_TGID);
3391 		rcu_read_unlock();
3392 		if (!task) {
3393 			err = -ESRCH;
3394 			goto error_path_put;
3395 		}
3396 	}
3397 
3398 	err = -ENOMEM;
3399 
3400 	link = kzalloc(sizeof(*link), GFP_KERNEL);
3401 	uprobes = kvcalloc(cnt, sizeof(*uprobes), GFP_KERNEL);
3402 
3403 	if (!uprobes || !link)
3404 		goto error_free;
3405 
3406 	for (i = 0; i < cnt; i++) {
3407 		if (__get_user(uprobes[i].offset, uoffsets + i)) {
3408 			err = -EFAULT;
3409 			goto error_free;
3410 		}
3411 		if (uprobes[i].offset < 0) {
3412 			err = -EINVAL;
3413 			goto error_free;
3414 		}
3415 		if (uref_ctr_offsets && __get_user(uprobes[i].ref_ctr_offset, uref_ctr_offsets + i)) {
3416 			err = -EFAULT;
3417 			goto error_free;
3418 		}
3419 		if (ucookies && __get_user(uprobes[i].cookie, ucookies + i)) {
3420 			err = -EFAULT;
3421 			goto error_free;
3422 		}
3423 
3424 		uprobes[i].link = link;
3425 
3426 		if (!(flags & BPF_F_UPROBE_MULTI_RETURN))
3427 			uprobes[i].consumer.handler = uprobe_multi_link_handler;
3428 		if (flags & BPF_F_UPROBE_MULTI_RETURN || is_uprobe_session(prog))
3429 			uprobes[i].consumer.ret_handler = uprobe_multi_link_ret_handler;
3430 		if (is_uprobe_session(prog))
3431 			uprobes[i].session = true;
3432 		if (pid)
3433 			uprobes[i].consumer.filter = uprobe_multi_link_filter;
3434 	}
3435 
3436 	link->cnt = cnt;
3437 	link->uprobes = uprobes;
3438 	link->path = path;
3439 	link->task = task;
3440 	link->link.flags = flags;
3441 
3442 	bpf_link_init(&link->link, BPF_LINK_TYPE_UPROBE_MULTI,
3443 		      &bpf_uprobe_multi_link_lops, prog, attr->link_create.attach_type);
3444 
3445 	for (i = 0; i < cnt; i++) {
3446 		uprobes[i].uprobe = uprobe_register(d_real_inode(link->path.dentry),
3447 						    uprobes[i].offset,
3448 						    uprobes[i].ref_ctr_offset,
3449 						    &uprobes[i].consumer);
3450 		if (IS_ERR(uprobes[i].uprobe)) {
3451 			err = PTR_ERR(uprobes[i].uprobe);
3452 			link->cnt = i;
3453 			goto error_unregister;
3454 		}
3455 	}
3456 
3457 	err = bpf_link_prime(&link->link, &link_primer);
3458 	if (err)
3459 		goto error_unregister;
3460 
3461 	return bpf_link_settle(&link_primer);
3462 
3463 error_unregister:
3464 	bpf_uprobe_unregister(uprobes, link->cnt);
3465 
3466 error_free:
3467 	kvfree(uprobes);
3468 	kfree(link);
3469 	if (task)
3470 		put_task_struct(task);
3471 error_path_put:
3472 	path_put(&path);
3473 	return err;
3474 }
3475 #else /* !CONFIG_UPROBES */
bpf_uprobe_multi_link_attach(const union bpf_attr * attr,struct bpf_prog * prog)3476 int bpf_uprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3477 {
3478 	return -EOPNOTSUPP;
3479 }
bpf_uprobe_multi_cookie(struct bpf_run_ctx * ctx)3480 static u64 bpf_uprobe_multi_cookie(struct bpf_run_ctx *ctx)
3481 {
3482 	return 0;
3483 }
bpf_uprobe_multi_entry_ip(struct bpf_run_ctx * ctx)3484 static u64 bpf_uprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
3485 {
3486 	return 0;
3487 }
3488 #endif /* CONFIG_UPROBES */
3489 
3490 __bpf_kfunc_start_defs();
3491 
bpf_session_is_return(void)3492 __bpf_kfunc bool bpf_session_is_return(void)
3493 {
3494 	struct bpf_session_run_ctx *session_ctx;
3495 
3496 	session_ctx = container_of(current->bpf_ctx, struct bpf_session_run_ctx, run_ctx);
3497 	return session_ctx->is_return;
3498 }
3499 
bpf_session_cookie(void)3500 __bpf_kfunc __u64 *bpf_session_cookie(void)
3501 {
3502 	struct bpf_session_run_ctx *session_ctx;
3503 
3504 	session_ctx = container_of(current->bpf_ctx, struct bpf_session_run_ctx, run_ctx);
3505 	return session_ctx->data;
3506 }
3507 
3508 __bpf_kfunc_end_defs();
3509 
3510 BTF_KFUNCS_START(kprobe_multi_kfunc_set_ids)
BTF_ID_FLAGS(func,bpf_session_is_return)3511 BTF_ID_FLAGS(func, bpf_session_is_return)
3512 BTF_ID_FLAGS(func, bpf_session_cookie)
3513 BTF_KFUNCS_END(kprobe_multi_kfunc_set_ids)
3514 
3515 static int bpf_kprobe_multi_filter(const struct bpf_prog *prog, u32 kfunc_id)
3516 {
3517 	if (!btf_id_set8_contains(&kprobe_multi_kfunc_set_ids, kfunc_id))
3518 		return 0;
3519 
3520 	if (!is_kprobe_session(prog) && !is_uprobe_session(prog))
3521 		return -EACCES;
3522 
3523 	return 0;
3524 }
3525 
3526 static const struct btf_kfunc_id_set bpf_kprobe_multi_kfunc_set = {
3527 	.owner = THIS_MODULE,
3528 	.set = &kprobe_multi_kfunc_set_ids,
3529 	.filter = bpf_kprobe_multi_filter,
3530 };
3531 
bpf_kprobe_multi_kfuncs_init(void)3532 static int __init bpf_kprobe_multi_kfuncs_init(void)
3533 {
3534 	return register_btf_kfunc_id_set(BPF_PROG_TYPE_KPROBE, &bpf_kprobe_multi_kfunc_set);
3535 }
3536 
3537 late_initcall(bpf_kprobe_multi_kfuncs_init);
3538 
3539 typedef int (*copy_fn_t)(void *dst, const void *src, u32 size, struct task_struct *tsk);
3540 
3541 /*
3542  * The __always_inline is to make sure the compiler doesn't
3543  * generate indirect calls into callbacks, which is expensive,
3544  * on some kernel configurations. This allows compiler to put
3545  * direct calls into all the specific callback implementations
3546  * (copy_user_data_sleepable, copy_user_data_nofault, and so on)
3547  */
__bpf_dynptr_copy_str(struct bpf_dynptr * dptr,u32 doff,u32 size,const void * unsafe_src,copy_fn_t str_copy_fn,struct task_struct * tsk)3548 static __always_inline int __bpf_dynptr_copy_str(struct bpf_dynptr *dptr, u32 doff, u32 size,
3549 						 const void *unsafe_src,
3550 						 copy_fn_t str_copy_fn,
3551 						 struct task_struct *tsk)
3552 {
3553 	struct bpf_dynptr_kern *dst;
3554 	u32 chunk_sz, off;
3555 	void *dst_slice;
3556 	int cnt, err;
3557 	char buf[256];
3558 
3559 	dst_slice = bpf_dynptr_slice_rdwr(dptr, doff, NULL, size);
3560 	if (likely(dst_slice))
3561 		return str_copy_fn(dst_slice, unsafe_src, size, tsk);
3562 
3563 	dst = (struct bpf_dynptr_kern *)dptr;
3564 	if (bpf_dynptr_check_off_len(dst, doff, size))
3565 		return -E2BIG;
3566 
3567 	for (off = 0; off < size; off += chunk_sz - 1) {
3568 		chunk_sz = min_t(u32, sizeof(buf), size - off);
3569 		/* Expect str_copy_fn to return count of copied bytes, including
3570 		 * zero terminator. Next iteration increment off by chunk_sz - 1 to
3571 		 * overwrite NUL.
3572 		 */
3573 		cnt = str_copy_fn(buf, unsafe_src + off, chunk_sz, tsk);
3574 		if (cnt < 0)
3575 			return cnt;
3576 		err = __bpf_dynptr_write(dst, doff + off, buf, cnt, 0);
3577 		if (err)
3578 			return err;
3579 		if (cnt < chunk_sz || chunk_sz == 1) /* we are done */
3580 			return off + cnt;
3581 	}
3582 	return off;
3583 }
3584 
__bpf_dynptr_copy(const struct bpf_dynptr * dptr,u32 doff,u32 size,const void * unsafe_src,copy_fn_t copy_fn,struct task_struct * tsk)3585 static __always_inline int __bpf_dynptr_copy(const struct bpf_dynptr *dptr, u32 doff,
3586 					     u32 size, const void *unsafe_src,
3587 					     copy_fn_t copy_fn, struct task_struct *tsk)
3588 {
3589 	struct bpf_dynptr_kern *dst;
3590 	void *dst_slice;
3591 	char buf[256];
3592 	u32 off, chunk_sz;
3593 	int err;
3594 
3595 	dst_slice = bpf_dynptr_slice_rdwr(dptr, doff, NULL, size);
3596 	if (likely(dst_slice))
3597 		return copy_fn(dst_slice, unsafe_src, size, tsk);
3598 
3599 	dst = (struct bpf_dynptr_kern *)dptr;
3600 	if (bpf_dynptr_check_off_len(dst, doff, size))
3601 		return -E2BIG;
3602 
3603 	for (off = 0; off < size; off += chunk_sz) {
3604 		chunk_sz = min_t(u32, sizeof(buf), size - off);
3605 		err = copy_fn(buf, unsafe_src + off, chunk_sz, tsk);
3606 		if (err)
3607 			return err;
3608 		err = __bpf_dynptr_write(dst, doff + off, buf, chunk_sz, 0);
3609 		if (err)
3610 			return err;
3611 	}
3612 	return 0;
3613 }
3614 
copy_user_data_nofault(void * dst,const void * unsafe_src,u32 size,struct task_struct * tsk)3615 static __always_inline int copy_user_data_nofault(void *dst, const void *unsafe_src,
3616 						  u32 size, struct task_struct *tsk)
3617 {
3618 	return copy_from_user_nofault(dst, (const void __user *)unsafe_src, size);
3619 }
3620 
copy_user_data_sleepable(void * dst,const void * unsafe_src,u32 size,struct task_struct * tsk)3621 static __always_inline int copy_user_data_sleepable(void *dst, const void *unsafe_src,
3622 						    u32 size, struct task_struct *tsk)
3623 {
3624 	int ret;
3625 
3626 	if (!tsk) { /* Read from the current task */
3627 		ret = copy_from_user(dst, (const void __user *)unsafe_src, size);
3628 		if (ret)
3629 			return -EFAULT;
3630 		return 0;
3631 	}
3632 
3633 	ret = access_process_vm(tsk, (unsigned long)unsafe_src, dst, size, 0);
3634 	if (ret != size)
3635 		return -EFAULT;
3636 	return 0;
3637 }
3638 
copy_kernel_data_nofault(void * dst,const void * unsafe_src,u32 size,struct task_struct * tsk)3639 static __always_inline int copy_kernel_data_nofault(void *dst, const void *unsafe_src,
3640 						    u32 size, struct task_struct *tsk)
3641 {
3642 	return copy_from_kernel_nofault(dst, unsafe_src, size);
3643 }
3644 
copy_user_str_nofault(void * dst,const void * unsafe_src,u32 size,struct task_struct * tsk)3645 static __always_inline int copy_user_str_nofault(void *dst, const void *unsafe_src,
3646 						 u32 size, struct task_struct *tsk)
3647 {
3648 	return strncpy_from_user_nofault(dst, (const void __user *)unsafe_src, size);
3649 }
3650 
copy_user_str_sleepable(void * dst,const void * unsafe_src,u32 size,struct task_struct * tsk)3651 static __always_inline int copy_user_str_sleepable(void *dst, const void *unsafe_src,
3652 						   u32 size, struct task_struct *tsk)
3653 {
3654 	int ret;
3655 
3656 	if (unlikely(size == 0))
3657 		return 0;
3658 
3659 	if (tsk) {
3660 		ret = copy_remote_vm_str(tsk, (unsigned long)unsafe_src, dst, size, 0);
3661 	} else {
3662 		ret = strncpy_from_user(dst, (const void __user *)unsafe_src, size - 1);
3663 		/* strncpy_from_user does not guarantee NUL termination */
3664 		if (ret >= 0)
3665 			((char *)dst)[ret] = '\0';
3666 	}
3667 
3668 	if (ret < 0)
3669 		return ret;
3670 	return ret + 1;
3671 }
3672 
copy_kernel_str_nofault(void * dst,const void * unsafe_src,u32 size,struct task_struct * tsk)3673 static __always_inline int copy_kernel_str_nofault(void *dst, const void *unsafe_src,
3674 						   u32 size, struct task_struct *tsk)
3675 {
3676 	return strncpy_from_kernel_nofault(dst, unsafe_src, size);
3677 }
3678 
3679 __bpf_kfunc_start_defs();
3680 
bpf_send_signal_task(struct task_struct * task,int sig,enum pid_type type,u64 value)3681 __bpf_kfunc int bpf_send_signal_task(struct task_struct *task, int sig, enum pid_type type,
3682 				     u64 value)
3683 {
3684 	if (type != PIDTYPE_PID && type != PIDTYPE_TGID)
3685 		return -EINVAL;
3686 
3687 	return bpf_send_signal_common(sig, type, task, value);
3688 }
3689 
bpf_probe_read_user_dynptr(struct bpf_dynptr * dptr,u32 off,u32 size,const void __user * unsafe_ptr__ign)3690 __bpf_kfunc int bpf_probe_read_user_dynptr(struct bpf_dynptr *dptr, u32 off,
3691 					   u32 size, const void __user *unsafe_ptr__ign)
3692 {
3693 	return __bpf_dynptr_copy(dptr, off, size, (const void *)unsafe_ptr__ign,
3694 				 copy_user_data_nofault, NULL);
3695 }
3696 
bpf_probe_read_kernel_dynptr(struct bpf_dynptr * dptr,u32 off,u32 size,const void * unsafe_ptr__ign)3697 __bpf_kfunc int bpf_probe_read_kernel_dynptr(struct bpf_dynptr *dptr, u32 off,
3698 					     u32 size, const void *unsafe_ptr__ign)
3699 {
3700 	return __bpf_dynptr_copy(dptr, off, size, unsafe_ptr__ign,
3701 				 copy_kernel_data_nofault, NULL);
3702 }
3703 
bpf_probe_read_user_str_dynptr(struct bpf_dynptr * dptr,u32 off,u32 size,const void __user * unsafe_ptr__ign)3704 __bpf_kfunc int bpf_probe_read_user_str_dynptr(struct bpf_dynptr *dptr, u32 off,
3705 					       u32 size, const void __user *unsafe_ptr__ign)
3706 {
3707 	return __bpf_dynptr_copy_str(dptr, off, size, (const void *)unsafe_ptr__ign,
3708 				     copy_user_str_nofault, NULL);
3709 }
3710 
bpf_probe_read_kernel_str_dynptr(struct bpf_dynptr * dptr,u32 off,u32 size,const void * unsafe_ptr__ign)3711 __bpf_kfunc int bpf_probe_read_kernel_str_dynptr(struct bpf_dynptr *dptr, u32 off,
3712 						 u32 size, const void *unsafe_ptr__ign)
3713 {
3714 	return __bpf_dynptr_copy_str(dptr, off, size, unsafe_ptr__ign,
3715 				     copy_kernel_str_nofault, NULL);
3716 }
3717 
bpf_copy_from_user_dynptr(struct bpf_dynptr * dptr,u32 off,u32 size,const void __user * unsafe_ptr__ign)3718 __bpf_kfunc int bpf_copy_from_user_dynptr(struct bpf_dynptr *dptr, u32 off,
3719 					  u32 size, const void __user *unsafe_ptr__ign)
3720 {
3721 	return __bpf_dynptr_copy(dptr, off, size, (const void *)unsafe_ptr__ign,
3722 				 copy_user_data_sleepable, NULL);
3723 }
3724 
bpf_copy_from_user_str_dynptr(struct bpf_dynptr * dptr,u32 off,u32 size,const void __user * unsafe_ptr__ign)3725 __bpf_kfunc int bpf_copy_from_user_str_dynptr(struct bpf_dynptr *dptr, u32 off,
3726 					      u32 size, const void __user *unsafe_ptr__ign)
3727 {
3728 	return __bpf_dynptr_copy_str(dptr, off, size, (const void *)unsafe_ptr__ign,
3729 				     copy_user_str_sleepable, NULL);
3730 }
3731 
bpf_copy_from_user_task_dynptr(struct bpf_dynptr * dptr,u32 off,u32 size,const void __user * unsafe_ptr__ign,struct task_struct * tsk)3732 __bpf_kfunc int bpf_copy_from_user_task_dynptr(struct bpf_dynptr *dptr, u32 off,
3733 					       u32 size, const void __user *unsafe_ptr__ign,
3734 					       struct task_struct *tsk)
3735 {
3736 	return __bpf_dynptr_copy(dptr, off, size, (const void *)unsafe_ptr__ign,
3737 				 copy_user_data_sleepable, tsk);
3738 }
3739 
bpf_copy_from_user_task_str_dynptr(struct bpf_dynptr * dptr,u32 off,u32 size,const void __user * unsafe_ptr__ign,struct task_struct * tsk)3740 __bpf_kfunc int bpf_copy_from_user_task_str_dynptr(struct bpf_dynptr *dptr, u32 off,
3741 						   u32 size, const void __user *unsafe_ptr__ign,
3742 						   struct task_struct *tsk)
3743 {
3744 	return __bpf_dynptr_copy_str(dptr, off, size, (const void *)unsafe_ptr__ign,
3745 				     copy_user_str_sleepable, tsk);
3746 }
3747 
3748 __bpf_kfunc_end_defs();
3749