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