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