• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_perf_event.h>
10 #include <linux/btf.h>
11 #include <linux/filter.h>
12 #include <linux/uaccess.h>
13 #include <linux/ctype.h>
14 #include <linux/kprobes.h>
15 #include <linux/spinlock.h>
16 #include <linux/syscalls.h>
17 #include <linux/error-injection.h>
18 #include <linux/btf_ids.h>
19 #include <linux/bpf_lsm.h>
20 #include <linux/fprobe.h>
21 #include <linux/bsearch.h>
22 #include <linux/sort.h>
23 #include <linux/key.h>
24 #include <linux/verification.h>
25 
26 #include <net/bpf_sk_storage.h>
27 
28 #include <uapi/linux/bpf.h>
29 #include <uapi/linux/btf.h>
30 
31 #include <asm/tlb.h>
32 
33 #include "trace_probe.h"
34 #include "trace.h"
35 
36 #define CREATE_TRACE_POINTS
37 #include "bpf_trace.h"
38 
39 #define bpf_event_rcu_dereference(p)					\
40 	rcu_dereference_protected(p, lockdep_is_held(&bpf_event_mutex))
41 
42 #ifdef CONFIG_MODULES
43 struct bpf_trace_module {
44 	struct module *module;
45 	struct list_head list;
46 };
47 
48 static LIST_HEAD(bpf_trace_modules);
49 static DEFINE_MUTEX(bpf_module_mutex);
50 
bpf_get_raw_tracepoint_module(const char * name)51 static struct bpf_raw_event_map *bpf_get_raw_tracepoint_module(const char *name)
52 {
53 	struct bpf_raw_event_map *btp, *ret = NULL;
54 	struct bpf_trace_module *btm;
55 	unsigned int i;
56 
57 	mutex_lock(&bpf_module_mutex);
58 	list_for_each_entry(btm, &bpf_trace_modules, list) {
59 		for (i = 0; i < btm->module->num_bpf_raw_events; ++i) {
60 			btp = &btm->module->bpf_raw_events[i];
61 			if (!strcmp(btp->tp->name, name)) {
62 				if (try_module_get(btm->module))
63 					ret = btp;
64 				goto out;
65 			}
66 		}
67 	}
68 out:
69 	mutex_unlock(&bpf_module_mutex);
70 	return ret;
71 }
72 #else
bpf_get_raw_tracepoint_module(const char * name)73 static struct bpf_raw_event_map *bpf_get_raw_tracepoint_module(const char *name)
74 {
75 	return NULL;
76 }
77 #endif /* CONFIG_MODULES */
78 
79 u64 bpf_get_stackid(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
80 u64 bpf_get_stack(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
81 
82 static int bpf_btf_printf_prepare(struct btf_ptr *ptr, u32 btf_ptr_size,
83 				  u64 flags, const struct btf **btf,
84 				  s32 *btf_id);
85 static u64 bpf_kprobe_multi_cookie(struct bpf_run_ctx *ctx);
86 static u64 bpf_kprobe_multi_entry_ip(struct bpf_run_ctx *ctx);
87 
88 /**
89  * trace_call_bpf - invoke BPF program
90  * @call: tracepoint event
91  * @ctx: opaque context pointer
92  *
93  * kprobe handlers execute BPF programs via this helper.
94  * Can be used from static tracepoints in the future.
95  *
96  * Return: BPF programs always return an integer which is interpreted by
97  * kprobe handler as:
98  * 0 - return from kprobe (event is filtered out)
99  * 1 - store kprobe event into ring buffer
100  * Other values are reserved and currently alias to 1
101  */
trace_call_bpf(struct trace_event_call * call,void * ctx)102 unsigned int trace_call_bpf(struct trace_event_call *call, void *ctx)
103 {
104 	unsigned int ret;
105 
106 	cant_sleep();
107 
108 	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) {
109 		/*
110 		 * since some bpf program is already running on this cpu,
111 		 * don't call into another bpf program (same or different)
112 		 * and don't send kprobe event into ring-buffer,
113 		 * so return zero here
114 		 */
115 		ret = 0;
116 		goto out;
117 	}
118 
119 	/*
120 	 * Instead of moving rcu_read_lock/rcu_dereference/rcu_read_unlock
121 	 * to all call sites, we did a bpf_prog_array_valid() there to check
122 	 * whether call->prog_array is empty or not, which is
123 	 * a heuristic to speed up execution.
124 	 *
125 	 * If bpf_prog_array_valid() fetched prog_array was
126 	 * non-NULL, we go into trace_call_bpf() and do the actual
127 	 * proper rcu_dereference() under RCU lock.
128 	 * If it turns out that prog_array is NULL then, we bail out.
129 	 * For the opposite, if the bpf_prog_array_valid() fetched pointer
130 	 * was NULL, you'll skip the prog_array with the risk of missing
131 	 * out of events when it was updated in between this and the
132 	 * rcu_dereference() which is accepted risk.
133 	 */
134 	rcu_read_lock();
135 	ret = bpf_prog_run_array(rcu_dereference(call->prog_array),
136 				 ctx, bpf_prog_run);
137 	rcu_read_unlock();
138 
139  out:
140 	__this_cpu_dec(bpf_prog_active);
141 
142 	return ret;
143 }
144 
145 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
BPF_CALL_2(bpf_override_return,struct pt_regs *,regs,unsigned long,rc)146 BPF_CALL_2(bpf_override_return, struct pt_regs *, regs, unsigned long, rc)
147 {
148 	regs_set_return_value(regs, rc);
149 	override_function_with_return(regs);
150 	return 0;
151 }
152 
153 static const struct bpf_func_proto bpf_override_return_proto = {
154 	.func		= bpf_override_return,
155 	.gpl_only	= true,
156 	.ret_type	= RET_INTEGER,
157 	.arg1_type	= ARG_PTR_TO_CTX,
158 	.arg2_type	= ARG_ANYTHING,
159 };
160 #endif
161 
162 static __always_inline int
bpf_probe_read_user_common(void * dst,u32 size,const void __user * unsafe_ptr)163 bpf_probe_read_user_common(void *dst, u32 size, const void __user *unsafe_ptr)
164 {
165 	int ret;
166 
167 	ret = copy_from_user_nofault(dst, unsafe_ptr, size);
168 	if (unlikely(ret < 0))
169 		memset(dst, 0, size);
170 	return ret;
171 }
172 
BPF_CALL_3(bpf_probe_read_user,void *,dst,u32,size,const void __user *,unsafe_ptr)173 BPF_CALL_3(bpf_probe_read_user, void *, dst, u32, size,
174 	   const void __user *, unsafe_ptr)
175 {
176 	return bpf_probe_read_user_common(dst, size, unsafe_ptr);
177 }
178 
179 const struct bpf_func_proto bpf_probe_read_user_proto = {
180 	.func		= bpf_probe_read_user,
181 	.gpl_only	= true,
182 	.ret_type	= RET_INTEGER,
183 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
184 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
185 	.arg3_type	= ARG_ANYTHING,
186 };
187 
188 static __always_inline int
bpf_probe_read_user_str_common(void * dst,u32 size,const void __user * unsafe_ptr)189 bpf_probe_read_user_str_common(void *dst, u32 size,
190 			       const void __user *unsafe_ptr)
191 {
192 	int ret;
193 
194 	/*
195 	 * NB: We rely on strncpy_from_user() not copying junk past the NUL
196 	 * terminator into `dst`.
197 	 *
198 	 * strncpy_from_user() does long-sized strides in the fast path. If the
199 	 * strncpy does not mask out the bytes after the NUL in `unsafe_ptr`,
200 	 * then there could be junk after the NUL in `dst`. If user takes `dst`
201 	 * and keys a hash map with it, then semantically identical strings can
202 	 * occupy multiple entries in the map.
203 	 */
204 	ret = strncpy_from_user_nofault(dst, unsafe_ptr, size);
205 	if (unlikely(ret < 0))
206 		memset(dst, 0, size);
207 	return ret;
208 }
209 
BPF_CALL_3(bpf_probe_read_user_str,void *,dst,u32,size,const void __user *,unsafe_ptr)210 BPF_CALL_3(bpf_probe_read_user_str, void *, dst, u32, size,
211 	   const void __user *, unsafe_ptr)
212 {
213 	return bpf_probe_read_user_str_common(dst, size, unsafe_ptr);
214 }
215 
216 const struct bpf_func_proto bpf_probe_read_user_str_proto = {
217 	.func		= bpf_probe_read_user_str,
218 	.gpl_only	= true,
219 	.ret_type	= RET_INTEGER,
220 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
221 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
222 	.arg3_type	= ARG_ANYTHING,
223 };
224 
225 static __always_inline int
bpf_probe_read_kernel_common(void * dst,u32 size,const void * unsafe_ptr)226 bpf_probe_read_kernel_common(void *dst, u32 size, const void *unsafe_ptr)
227 {
228 	int ret;
229 
230 	ret = copy_from_kernel_nofault(dst, unsafe_ptr, size);
231 	if (unlikely(ret < 0))
232 		memset(dst, 0, size);
233 	return ret;
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 
bpf_get_probe_write_proto(void)360 static const struct bpf_func_proto *bpf_get_probe_write_proto(void)
361 {
362 	if (!capable(CAP_SYS_ADMIN))
363 		return NULL;
364 
365 	pr_warn_ratelimited("%s[%d] is installing a program with bpf_probe_write_user helper that may corrupt user memory!",
366 			    current->comm, task_pid_nr(current));
367 
368 	return &bpf_probe_write_user_proto;
369 }
370 
371 #define MAX_TRACE_PRINTK_VARARGS	3
372 #define BPF_TRACE_PRINTK_SIZE		1024
373 
BPF_CALL_5(bpf_trace_printk,char *,fmt,u32,fmt_size,u64,arg1,u64,arg2,u64,arg3)374 BPF_CALL_5(bpf_trace_printk, char *, fmt, u32, fmt_size, u64, arg1,
375 	   u64, arg2, u64, arg3)
376 {
377 	u64 args[MAX_TRACE_PRINTK_VARARGS] = { arg1, arg2, arg3 };
378 	struct bpf_bprintf_data data = {
379 		.get_bin_args	= true,
380 		.get_buf	= true,
381 	};
382 	int ret;
383 
384 	ret = bpf_bprintf_prepare(fmt, fmt_size, args,
385 				  MAX_TRACE_PRINTK_VARARGS, &data);
386 	if (ret < 0)
387 		return ret;
388 
389 	ret = bstr_printf(data.buf, MAX_BPRINTF_BUF, fmt, data.bin_args);
390 
391 	trace_bpf_trace_printk(data.buf);
392 
393 	bpf_bprintf_cleanup(&data);
394 
395 	return ret;
396 }
397 
398 static const struct bpf_func_proto bpf_trace_printk_proto = {
399 	.func		= bpf_trace_printk,
400 	.gpl_only	= true,
401 	.ret_type	= RET_INTEGER,
402 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
403 	.arg2_type	= ARG_CONST_SIZE,
404 };
405 
__set_printk_clr_event(void)406 static void __set_printk_clr_event(void)
407 {
408 	/*
409 	 * This program might be calling bpf_trace_printk,
410 	 * so enable the associated bpf_trace/bpf_trace_printk event.
411 	 * Repeat this each time as it is possible a user has
412 	 * disabled bpf_trace_printk events.  By loading a program
413 	 * calling bpf_trace_printk() however the user has expressed
414 	 * the intent to see such events.
415 	 */
416 	if (trace_set_clr_event("bpf_trace", "bpf_trace_printk", 1))
417 		pr_warn_ratelimited("could not enable bpf_trace_printk events");
418 }
419 
bpf_get_trace_printk_proto(void)420 const struct bpf_func_proto *bpf_get_trace_printk_proto(void)
421 {
422 	__set_printk_clr_event();
423 	return &bpf_trace_printk_proto;
424 }
425 
BPF_CALL_4(bpf_trace_vprintk,char *,fmt,u32,fmt_size,const void *,args,u32,data_len)426 BPF_CALL_4(bpf_trace_vprintk, char *, fmt, u32, fmt_size, const void *, args,
427 	   u32, data_len)
428 {
429 	struct bpf_bprintf_data data = {
430 		.get_bin_args	= true,
431 		.get_buf	= true,
432 	};
433 	int ret, num_args;
434 
435 	if (data_len & 7 || data_len > MAX_BPRINTF_VARARGS * 8 ||
436 	    (data_len && !args))
437 		return -EINVAL;
438 	num_args = data_len / 8;
439 
440 	ret = bpf_bprintf_prepare(fmt, fmt_size, args, num_args, &data);
441 	if (ret < 0)
442 		return ret;
443 
444 	ret = bstr_printf(data.buf, MAX_BPRINTF_BUF, fmt, data.bin_args);
445 
446 	trace_bpf_trace_printk(data.buf);
447 
448 	bpf_bprintf_cleanup(&data);
449 
450 	return ret;
451 }
452 
453 static const struct bpf_func_proto bpf_trace_vprintk_proto = {
454 	.func		= bpf_trace_vprintk,
455 	.gpl_only	= true,
456 	.ret_type	= RET_INTEGER,
457 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
458 	.arg2_type	= ARG_CONST_SIZE,
459 	.arg3_type	= ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
460 	.arg4_type	= ARG_CONST_SIZE_OR_ZERO,
461 };
462 
bpf_get_trace_vprintk_proto(void)463 const struct bpf_func_proto *bpf_get_trace_vprintk_proto(void)
464 {
465 	__set_printk_clr_event();
466 	return &bpf_trace_vprintk_proto;
467 }
468 
BPF_CALL_5(bpf_seq_printf,struct seq_file *,m,char *,fmt,u32,fmt_size,const void *,args,u32,data_len)469 BPF_CALL_5(bpf_seq_printf, struct seq_file *, m, char *, fmt, u32, fmt_size,
470 	   const void *, args, u32, data_len)
471 {
472 	struct bpf_bprintf_data data = {
473 		.get_bin_args	= true,
474 	};
475 	int err, num_args;
476 
477 	if (data_len & 7 || data_len > MAX_BPRINTF_VARARGS * 8 ||
478 	    (data_len && !args))
479 		return -EINVAL;
480 	num_args = data_len / 8;
481 
482 	err = bpf_bprintf_prepare(fmt, fmt_size, args, num_args, &data);
483 	if (err < 0)
484 		return err;
485 
486 	seq_bprintf(m, fmt, data.bin_args);
487 
488 	bpf_bprintf_cleanup(&data);
489 
490 	return seq_has_overflowed(m) ? -EOVERFLOW : 0;
491 }
492 
493 BTF_ID_LIST_SINGLE(btf_seq_file_ids, struct, seq_file)
494 
495 static const struct bpf_func_proto bpf_seq_printf_proto = {
496 	.func		= bpf_seq_printf,
497 	.gpl_only	= true,
498 	.ret_type	= RET_INTEGER,
499 	.arg1_type	= ARG_PTR_TO_BTF_ID,
500 	.arg1_btf_id	= &btf_seq_file_ids[0],
501 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
502 	.arg3_type	= ARG_CONST_SIZE,
503 	.arg4_type      = ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
504 	.arg5_type      = ARG_CONST_SIZE_OR_ZERO,
505 };
506 
BPF_CALL_3(bpf_seq_write,struct seq_file *,m,const void *,data,u32,len)507 BPF_CALL_3(bpf_seq_write, struct seq_file *, m, const void *, data, u32, len)
508 {
509 	return seq_write(m, data, len) ? -EOVERFLOW : 0;
510 }
511 
512 static const struct bpf_func_proto bpf_seq_write_proto = {
513 	.func		= bpf_seq_write,
514 	.gpl_only	= true,
515 	.ret_type	= RET_INTEGER,
516 	.arg1_type	= ARG_PTR_TO_BTF_ID,
517 	.arg1_btf_id	= &btf_seq_file_ids[0],
518 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
519 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
520 };
521 
BPF_CALL_4(bpf_seq_printf_btf,struct seq_file *,m,struct btf_ptr *,ptr,u32,btf_ptr_size,u64,flags)522 BPF_CALL_4(bpf_seq_printf_btf, struct seq_file *, m, struct btf_ptr *, ptr,
523 	   u32, btf_ptr_size, u64, flags)
524 {
525 	const struct btf *btf;
526 	s32 btf_id;
527 	int ret;
528 
529 	ret = bpf_btf_printf_prepare(ptr, btf_ptr_size, flags, &btf, &btf_id);
530 	if (ret)
531 		return ret;
532 
533 	return btf_type_seq_show_flags(btf, btf_id, ptr->ptr, m, flags);
534 }
535 
536 static const struct bpf_func_proto bpf_seq_printf_btf_proto = {
537 	.func		= bpf_seq_printf_btf,
538 	.gpl_only	= true,
539 	.ret_type	= RET_INTEGER,
540 	.arg1_type	= ARG_PTR_TO_BTF_ID,
541 	.arg1_btf_id	= &btf_seq_file_ids[0],
542 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
543 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
544 	.arg4_type	= ARG_ANYTHING,
545 };
546 
547 static __always_inline int
get_map_perf_counter(struct bpf_map * map,u64 flags,u64 * value,u64 * enabled,u64 * running)548 get_map_perf_counter(struct bpf_map *map, u64 flags,
549 		     u64 *value, u64 *enabled, u64 *running)
550 {
551 	struct bpf_array *array = container_of(map, struct bpf_array, map);
552 	unsigned int cpu = smp_processor_id();
553 	u64 index = flags & BPF_F_INDEX_MASK;
554 	struct bpf_event_entry *ee;
555 
556 	if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
557 		return -EINVAL;
558 	if (index == BPF_F_CURRENT_CPU)
559 		index = cpu;
560 	if (unlikely(index >= array->map.max_entries))
561 		return -E2BIG;
562 
563 	ee = READ_ONCE(array->ptrs[index]);
564 	if (!ee)
565 		return -ENOENT;
566 
567 	return perf_event_read_local(ee->event, value, enabled, running);
568 }
569 
BPF_CALL_2(bpf_perf_event_read,struct bpf_map *,map,u64,flags)570 BPF_CALL_2(bpf_perf_event_read, struct bpf_map *, map, u64, flags)
571 {
572 	u64 value = 0;
573 	int err;
574 
575 	err = get_map_perf_counter(map, flags, &value, NULL, NULL);
576 	/*
577 	 * this api is ugly since we miss [-22..-2] range of valid
578 	 * counter values, but that's uapi
579 	 */
580 	if (err)
581 		return err;
582 	return value;
583 }
584 
585 static const struct bpf_func_proto bpf_perf_event_read_proto = {
586 	.func		= bpf_perf_event_read,
587 	.gpl_only	= true,
588 	.ret_type	= RET_INTEGER,
589 	.arg1_type	= ARG_CONST_MAP_PTR,
590 	.arg2_type	= ARG_ANYTHING,
591 };
592 
BPF_CALL_4(bpf_perf_event_read_value,struct bpf_map *,map,u64,flags,struct bpf_perf_event_value *,buf,u32,size)593 BPF_CALL_4(bpf_perf_event_read_value, struct bpf_map *, map, u64, flags,
594 	   struct bpf_perf_event_value *, buf, u32, size)
595 {
596 	int err = -EINVAL;
597 
598 	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
599 		goto clear;
600 	err = get_map_perf_counter(map, flags, &buf->counter, &buf->enabled,
601 				   &buf->running);
602 	if (unlikely(err))
603 		goto clear;
604 	return 0;
605 clear:
606 	memset(buf, 0, size);
607 	return err;
608 }
609 
610 static const struct bpf_func_proto bpf_perf_event_read_value_proto = {
611 	.func		= bpf_perf_event_read_value,
612 	.gpl_only	= true,
613 	.ret_type	= RET_INTEGER,
614 	.arg1_type	= ARG_CONST_MAP_PTR,
615 	.arg2_type	= ARG_ANYTHING,
616 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
617 	.arg4_type	= ARG_CONST_SIZE,
618 };
619 
620 static __always_inline u64
__bpf_perf_event_output(struct pt_regs * regs,struct bpf_map * map,u64 flags,struct perf_sample_data * sd)621 __bpf_perf_event_output(struct pt_regs *regs, struct bpf_map *map,
622 			u64 flags, struct perf_sample_data *sd)
623 {
624 	struct bpf_array *array = container_of(map, struct bpf_array, map);
625 	unsigned int cpu = smp_processor_id();
626 	u64 index = flags & BPF_F_INDEX_MASK;
627 	struct bpf_event_entry *ee;
628 	struct perf_event *event;
629 
630 	if (index == BPF_F_CURRENT_CPU)
631 		index = cpu;
632 	if (unlikely(index >= array->map.max_entries))
633 		return -E2BIG;
634 
635 	ee = READ_ONCE(array->ptrs[index]);
636 	if (!ee)
637 		return -ENOENT;
638 
639 	event = ee->event;
640 	if (unlikely(event->attr.type != PERF_TYPE_SOFTWARE ||
641 		     event->attr.config != PERF_COUNT_SW_BPF_OUTPUT))
642 		return -EINVAL;
643 
644 	if (unlikely(event->oncpu != cpu))
645 		return -EOPNOTSUPP;
646 
647 	return perf_event_output(event, sd, regs);
648 }
649 
650 /*
651  * Support executing tracepoints in normal, irq, and nmi context that each call
652  * bpf_perf_event_output
653  */
654 struct bpf_trace_sample_data {
655 	struct perf_sample_data sds[3];
656 };
657 
658 static DEFINE_PER_CPU(struct bpf_trace_sample_data, bpf_trace_sds);
659 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)660 BPF_CALL_5(bpf_perf_event_output, struct pt_regs *, regs, struct bpf_map *, map,
661 	   u64, flags, void *, data, u64, size)
662 {
663 	struct bpf_trace_sample_data *sds;
664 	struct perf_raw_record raw = {
665 		.frag = {
666 			.size = size,
667 			.data = data,
668 		},
669 	};
670 	struct perf_sample_data *sd;
671 	int nest_level, err;
672 
673 	preempt_disable();
674 	sds = this_cpu_ptr(&bpf_trace_sds);
675 	nest_level = this_cpu_inc_return(bpf_trace_nest_level);
676 
677 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(sds->sds))) {
678 		err = -EBUSY;
679 		goto out;
680 	}
681 
682 	sd = &sds->sds[nest_level - 1];
683 
684 	if (unlikely(flags & ~(BPF_F_INDEX_MASK))) {
685 		err = -EINVAL;
686 		goto out;
687 	}
688 
689 	perf_sample_data_init(sd, 0, 0);
690 	sd->raw = &raw;
691 	sd->sample_flags |= PERF_SAMPLE_RAW;
692 
693 	err = __bpf_perf_event_output(regs, map, flags, sd);
694 out:
695 	this_cpu_dec(bpf_trace_nest_level);
696 	preempt_enable();
697 	return err;
698 }
699 
700 static const struct bpf_func_proto bpf_perf_event_output_proto = {
701 	.func		= bpf_perf_event_output,
702 	.gpl_only	= true,
703 	.ret_type	= RET_INTEGER,
704 	.arg1_type	= ARG_PTR_TO_CTX,
705 	.arg2_type	= ARG_CONST_MAP_PTR,
706 	.arg3_type	= ARG_ANYTHING,
707 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
708 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
709 };
710 
711 static DEFINE_PER_CPU(int, bpf_event_output_nest_level);
712 struct bpf_nested_pt_regs {
713 	struct pt_regs regs[3];
714 };
715 static DEFINE_PER_CPU(struct bpf_nested_pt_regs, bpf_pt_regs);
716 static DEFINE_PER_CPU(struct bpf_trace_sample_data, bpf_misc_sds);
717 
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)718 u64 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
719 		     void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
720 {
721 	struct perf_raw_frag frag = {
722 		.copy		= ctx_copy,
723 		.size		= ctx_size,
724 		.data		= ctx,
725 	};
726 	struct perf_raw_record raw = {
727 		.frag = {
728 			{
729 				.next	= ctx_size ? &frag : NULL,
730 			},
731 			.size	= meta_size,
732 			.data	= meta,
733 		},
734 	};
735 	struct perf_sample_data *sd;
736 	struct pt_regs *regs;
737 	int nest_level;
738 	u64 ret;
739 
740 	preempt_disable();
741 	nest_level = this_cpu_inc_return(bpf_event_output_nest_level);
742 
743 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(bpf_misc_sds.sds))) {
744 		ret = -EBUSY;
745 		goto out;
746 	}
747 	sd = this_cpu_ptr(&bpf_misc_sds.sds[nest_level - 1]);
748 	regs = this_cpu_ptr(&bpf_pt_regs.regs[nest_level - 1]);
749 
750 	perf_fetch_caller_regs(regs);
751 	perf_sample_data_init(sd, 0, 0);
752 	sd->raw = &raw;
753 	sd->sample_flags |= PERF_SAMPLE_RAW;
754 
755 	ret = __bpf_perf_event_output(regs, map, flags, sd);
756 out:
757 	this_cpu_dec(bpf_event_output_nest_level);
758 	preempt_enable();
759 	return ret;
760 }
761 
BPF_CALL_0(bpf_get_current_task)762 BPF_CALL_0(bpf_get_current_task)
763 {
764 	return (long) current;
765 }
766 
767 const struct bpf_func_proto bpf_get_current_task_proto = {
768 	.func		= bpf_get_current_task,
769 	.gpl_only	= true,
770 	.ret_type	= RET_INTEGER,
771 };
772 
BPF_CALL_0(bpf_get_current_task_btf)773 BPF_CALL_0(bpf_get_current_task_btf)
774 {
775 	return (unsigned long) current;
776 }
777 
778 const struct bpf_func_proto bpf_get_current_task_btf_proto = {
779 	.func		= bpf_get_current_task_btf,
780 	.gpl_only	= true,
781 	.ret_type	= RET_PTR_TO_BTF_ID,
782 	.ret_btf_id	= &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
783 };
784 
BPF_CALL_1(bpf_task_pt_regs,struct task_struct *,task)785 BPF_CALL_1(bpf_task_pt_regs, struct task_struct *, task)
786 {
787 	return (unsigned long) task_pt_regs(task);
788 }
789 
790 BTF_ID_LIST(bpf_task_pt_regs_ids)
791 BTF_ID(struct, pt_regs)
792 
793 const struct bpf_func_proto bpf_task_pt_regs_proto = {
794 	.func		= bpf_task_pt_regs,
795 	.gpl_only	= true,
796 	.arg1_type	= ARG_PTR_TO_BTF_ID,
797 	.arg1_btf_id	= &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
798 	.ret_type	= RET_PTR_TO_BTF_ID,
799 	.ret_btf_id	= &bpf_task_pt_regs_ids[0],
800 };
801 
BPF_CALL_2(bpf_current_task_under_cgroup,struct bpf_map *,map,u32,idx)802 BPF_CALL_2(bpf_current_task_under_cgroup, struct bpf_map *, map, u32, idx)
803 {
804 	struct bpf_array *array = container_of(map, struct bpf_array, map);
805 	struct cgroup *cgrp;
806 
807 	if (unlikely(idx >= array->map.max_entries))
808 		return -E2BIG;
809 
810 	cgrp = READ_ONCE(array->ptrs[idx]);
811 	if (unlikely(!cgrp))
812 		return -EAGAIN;
813 
814 	return task_under_cgroup_hierarchy(current, cgrp);
815 }
816 
817 static const struct bpf_func_proto bpf_current_task_under_cgroup_proto = {
818 	.func           = bpf_current_task_under_cgroup,
819 	.gpl_only       = false,
820 	.ret_type       = RET_INTEGER,
821 	.arg1_type      = ARG_CONST_MAP_PTR,
822 	.arg2_type      = ARG_ANYTHING,
823 };
824 
825 struct send_signal_irq_work {
826 	struct irq_work irq_work;
827 	struct task_struct *task;
828 	u32 sig;
829 	enum pid_type type;
830 };
831 
832 static DEFINE_PER_CPU(struct send_signal_irq_work, send_signal_work);
833 
do_bpf_send_signal(struct irq_work * entry)834 static void do_bpf_send_signal(struct irq_work *entry)
835 {
836 	struct send_signal_irq_work *work;
837 
838 	work = container_of(entry, struct send_signal_irq_work, irq_work);
839 	group_send_sig_info(work->sig, SEND_SIG_PRIV, work->task, work->type);
840 	put_task_struct(work->task);
841 }
842 
bpf_send_signal_common(u32 sig,enum pid_type type)843 static int bpf_send_signal_common(u32 sig, enum pid_type type)
844 {
845 	struct send_signal_irq_work *work = NULL;
846 
847 	/* Similar to bpf_probe_write_user, task needs to be
848 	 * in a sound condition and kernel memory access be
849 	 * permitted in order to send signal to the current
850 	 * task.
851 	 */
852 	if (unlikely(current->flags & (PF_KTHREAD | PF_EXITING)))
853 		return -EPERM;
854 	if (unlikely(!nmi_uaccess_okay()))
855 		return -EPERM;
856 	/* Task should not be pid=1 to avoid kernel panic. */
857 	if (unlikely(is_global_init(current)))
858 		return -EPERM;
859 
860 	if (irqs_disabled()) {
861 		/* Do an early check on signal validity. Otherwise,
862 		 * the error is lost in deferred irq_work.
863 		 */
864 		if (unlikely(!valid_signal(sig)))
865 			return -EINVAL;
866 
867 		work = this_cpu_ptr(&send_signal_work);
868 		if (irq_work_is_busy(&work->irq_work))
869 			return -EBUSY;
870 
871 		/* Add the current task, which is the target of sending signal,
872 		 * to the irq_work. The current task may change when queued
873 		 * irq works get executed.
874 		 */
875 		work->task = get_task_struct(current);
876 		work->sig = sig;
877 		work->type = type;
878 		irq_work_queue(&work->irq_work);
879 		return 0;
880 	}
881 
882 	return group_send_sig_info(sig, SEND_SIG_PRIV, current, type);
883 }
884 
BPF_CALL_1(bpf_send_signal,u32,sig)885 BPF_CALL_1(bpf_send_signal, u32, sig)
886 {
887 	return bpf_send_signal_common(sig, PIDTYPE_TGID);
888 }
889 
890 static const struct bpf_func_proto bpf_send_signal_proto = {
891 	.func		= bpf_send_signal,
892 	.gpl_only	= false,
893 	.ret_type	= RET_INTEGER,
894 	.arg1_type	= ARG_ANYTHING,
895 };
896 
BPF_CALL_1(bpf_send_signal_thread,u32,sig)897 BPF_CALL_1(bpf_send_signal_thread, u32, sig)
898 {
899 	return bpf_send_signal_common(sig, PIDTYPE_PID);
900 }
901 
902 static const struct bpf_func_proto bpf_send_signal_thread_proto = {
903 	.func		= bpf_send_signal_thread,
904 	.gpl_only	= false,
905 	.ret_type	= RET_INTEGER,
906 	.arg1_type	= ARG_ANYTHING,
907 };
908 
BPF_CALL_3(bpf_d_path,struct path *,path,char *,buf,u32,sz)909 BPF_CALL_3(bpf_d_path, struct path *, path, char *, buf, u32, sz)
910 {
911 	struct path copy;
912 	long len;
913 	char *p;
914 
915 	if (!sz)
916 		return 0;
917 
918 	/*
919 	 * The path pointer is verified as trusted and safe to use,
920 	 * but let's double check it's valid anyway to workaround
921 	 * potentially broken verifier.
922 	 */
923 	len = copy_from_kernel_nofault(&copy, path, sizeof(*path));
924 	if (len < 0)
925 		return len;
926 
927 	p = d_path(&copy, buf, sz);
928 	if (IS_ERR(p)) {
929 		len = PTR_ERR(p);
930 	} else {
931 		len = buf + sz - p;
932 		memmove(buf, p, len);
933 	}
934 
935 	return len;
936 }
937 
938 BTF_SET_START(btf_allowlist_d_path)
939 #ifdef CONFIG_SECURITY
BTF_ID(func,security_file_permission)940 BTF_ID(func, security_file_permission)
941 BTF_ID(func, security_inode_getattr)
942 BTF_ID(func, security_file_open)
943 #endif
944 #ifdef CONFIG_SECURITY_PATH
945 BTF_ID(func, security_path_truncate)
946 #endif
947 BTF_ID(func, vfs_truncate)
948 BTF_ID(func, vfs_fallocate)
949 BTF_ID(func, dentry_open)
950 BTF_ID(func, vfs_getattr)
951 BTF_ID(func, filp_close)
952 BTF_SET_END(btf_allowlist_d_path)
953 
954 static bool bpf_d_path_allowed(const struct bpf_prog *prog)
955 {
956 	if (prog->type == BPF_PROG_TYPE_TRACING &&
957 	    prog->expected_attach_type == BPF_TRACE_ITER)
958 		return true;
959 
960 	if (prog->type == BPF_PROG_TYPE_LSM)
961 		return bpf_lsm_is_sleepable_hook(prog->aux->attach_btf_id);
962 
963 	return btf_id_set_contains(&btf_allowlist_d_path,
964 				   prog->aux->attach_btf_id);
965 }
966 
967 BTF_ID_LIST_SINGLE(bpf_d_path_btf_ids, struct, path)
968 
969 static const struct bpf_func_proto bpf_d_path_proto = {
970 	.func		= bpf_d_path,
971 	.gpl_only	= false,
972 	.ret_type	= RET_INTEGER,
973 	.arg1_type	= ARG_PTR_TO_BTF_ID,
974 	.arg1_btf_id	= &bpf_d_path_btf_ids[0],
975 	.arg2_type	= ARG_PTR_TO_MEM,
976 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
977 	.allowed	= bpf_d_path_allowed,
978 };
979 
980 #define BTF_F_ALL	(BTF_F_COMPACT  | BTF_F_NONAME | \
981 			 BTF_F_PTR_RAW | BTF_F_ZERO)
982 
bpf_btf_printf_prepare(struct btf_ptr * ptr,u32 btf_ptr_size,u64 flags,const struct btf ** btf,s32 * btf_id)983 static int bpf_btf_printf_prepare(struct btf_ptr *ptr, u32 btf_ptr_size,
984 				  u64 flags, const struct btf **btf,
985 				  s32 *btf_id)
986 {
987 	const struct btf_type *t;
988 
989 	if (unlikely(flags & ~(BTF_F_ALL)))
990 		return -EINVAL;
991 
992 	if (btf_ptr_size != sizeof(struct btf_ptr))
993 		return -EINVAL;
994 
995 	*btf = bpf_get_btf_vmlinux();
996 
997 	if (IS_ERR_OR_NULL(*btf))
998 		return IS_ERR(*btf) ? PTR_ERR(*btf) : -EINVAL;
999 
1000 	if (ptr->type_id > 0)
1001 		*btf_id = ptr->type_id;
1002 	else
1003 		return -EINVAL;
1004 
1005 	if (*btf_id > 0)
1006 		t = btf_type_by_id(*btf, *btf_id);
1007 	if (*btf_id <= 0 || !t)
1008 		return -ENOENT;
1009 
1010 	return 0;
1011 }
1012 
BPF_CALL_5(bpf_snprintf_btf,char *,str,u32,str_size,struct btf_ptr *,ptr,u32,btf_ptr_size,u64,flags)1013 BPF_CALL_5(bpf_snprintf_btf, char *, str, u32, str_size, struct btf_ptr *, ptr,
1014 	   u32, btf_ptr_size, u64, flags)
1015 {
1016 	const struct btf *btf;
1017 	s32 btf_id;
1018 	int ret;
1019 
1020 	ret = bpf_btf_printf_prepare(ptr, btf_ptr_size, flags, &btf, &btf_id);
1021 	if (ret)
1022 		return ret;
1023 
1024 	return btf_type_snprintf_show(btf, btf_id, ptr->ptr, str, str_size,
1025 				      flags);
1026 }
1027 
1028 const struct bpf_func_proto bpf_snprintf_btf_proto = {
1029 	.func		= bpf_snprintf_btf,
1030 	.gpl_only	= false,
1031 	.ret_type	= RET_INTEGER,
1032 	.arg1_type	= ARG_PTR_TO_MEM,
1033 	.arg2_type	= ARG_CONST_SIZE,
1034 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1035 	.arg4_type	= ARG_CONST_SIZE,
1036 	.arg5_type	= ARG_ANYTHING,
1037 };
1038 
BPF_CALL_1(bpf_get_func_ip_tracing,void *,ctx)1039 BPF_CALL_1(bpf_get_func_ip_tracing, void *, ctx)
1040 {
1041 	/* This helper call is inlined by verifier. */
1042 	return ((u64 *)ctx)[-2];
1043 }
1044 
1045 static const struct bpf_func_proto bpf_get_func_ip_proto_tracing = {
1046 	.func		= bpf_get_func_ip_tracing,
1047 	.gpl_only	= true,
1048 	.ret_type	= RET_INTEGER,
1049 	.arg1_type	= ARG_PTR_TO_CTX,
1050 };
1051 
1052 #ifdef CONFIG_X86_KERNEL_IBT
get_entry_ip(unsigned long fentry_ip)1053 static unsigned long get_entry_ip(unsigned long fentry_ip)
1054 {
1055 	u32 instr;
1056 
1057 	/* Being extra safe in here in case entry ip is on the page-edge. */
1058 	if (get_kernel_nofault(instr, (u32 *) fentry_ip - 1))
1059 		return fentry_ip;
1060 	if (is_endbr(instr))
1061 		fentry_ip -= ENDBR_INSN_SIZE;
1062 	return fentry_ip;
1063 }
1064 #else
1065 #define get_entry_ip(fentry_ip) fentry_ip
1066 #endif
1067 
BPF_CALL_1(bpf_get_func_ip_kprobe,struct pt_regs *,regs)1068 BPF_CALL_1(bpf_get_func_ip_kprobe, struct pt_regs *, regs)
1069 {
1070 	struct kprobe *kp = kprobe_running();
1071 
1072 	if (!kp || !(kp->flags & KPROBE_FLAG_ON_FUNC_ENTRY))
1073 		return 0;
1074 
1075 	return get_entry_ip((uintptr_t)kp->addr);
1076 }
1077 
1078 static const struct bpf_func_proto bpf_get_func_ip_proto_kprobe = {
1079 	.func		= bpf_get_func_ip_kprobe,
1080 	.gpl_only	= true,
1081 	.ret_type	= RET_INTEGER,
1082 	.arg1_type	= ARG_PTR_TO_CTX,
1083 };
1084 
BPF_CALL_1(bpf_get_func_ip_kprobe_multi,struct pt_regs *,regs)1085 BPF_CALL_1(bpf_get_func_ip_kprobe_multi, struct pt_regs *, regs)
1086 {
1087 	return bpf_kprobe_multi_entry_ip(current->bpf_ctx);
1088 }
1089 
1090 static const struct bpf_func_proto bpf_get_func_ip_proto_kprobe_multi = {
1091 	.func		= bpf_get_func_ip_kprobe_multi,
1092 	.gpl_only	= false,
1093 	.ret_type	= RET_INTEGER,
1094 	.arg1_type	= ARG_PTR_TO_CTX,
1095 };
1096 
BPF_CALL_1(bpf_get_attach_cookie_kprobe_multi,struct pt_regs *,regs)1097 BPF_CALL_1(bpf_get_attach_cookie_kprobe_multi, struct pt_regs *, regs)
1098 {
1099 	return bpf_kprobe_multi_cookie(current->bpf_ctx);
1100 }
1101 
1102 static const struct bpf_func_proto bpf_get_attach_cookie_proto_kmulti = {
1103 	.func		= bpf_get_attach_cookie_kprobe_multi,
1104 	.gpl_only	= false,
1105 	.ret_type	= RET_INTEGER,
1106 	.arg1_type	= ARG_PTR_TO_CTX,
1107 };
1108 
BPF_CALL_1(bpf_get_attach_cookie_trace,void *,ctx)1109 BPF_CALL_1(bpf_get_attach_cookie_trace, void *, ctx)
1110 {
1111 	struct bpf_trace_run_ctx *run_ctx;
1112 
1113 	run_ctx = container_of(current->bpf_ctx, struct bpf_trace_run_ctx, run_ctx);
1114 	return run_ctx->bpf_cookie;
1115 }
1116 
1117 static const struct bpf_func_proto bpf_get_attach_cookie_proto_trace = {
1118 	.func		= bpf_get_attach_cookie_trace,
1119 	.gpl_only	= false,
1120 	.ret_type	= RET_INTEGER,
1121 	.arg1_type	= ARG_PTR_TO_CTX,
1122 };
1123 
BPF_CALL_1(bpf_get_attach_cookie_pe,struct bpf_perf_event_data_kern *,ctx)1124 BPF_CALL_1(bpf_get_attach_cookie_pe, struct bpf_perf_event_data_kern *, ctx)
1125 {
1126 	return ctx->event->bpf_cookie;
1127 }
1128 
1129 static const struct bpf_func_proto bpf_get_attach_cookie_proto_pe = {
1130 	.func		= bpf_get_attach_cookie_pe,
1131 	.gpl_only	= false,
1132 	.ret_type	= RET_INTEGER,
1133 	.arg1_type	= ARG_PTR_TO_CTX,
1134 };
1135 
BPF_CALL_1(bpf_get_attach_cookie_tracing,void *,ctx)1136 BPF_CALL_1(bpf_get_attach_cookie_tracing, void *, ctx)
1137 {
1138 	struct bpf_trace_run_ctx *run_ctx;
1139 
1140 	run_ctx = container_of(current->bpf_ctx, struct bpf_trace_run_ctx, run_ctx);
1141 	return run_ctx->bpf_cookie;
1142 }
1143 
1144 static const struct bpf_func_proto bpf_get_attach_cookie_proto_tracing = {
1145 	.func		= bpf_get_attach_cookie_tracing,
1146 	.gpl_only	= false,
1147 	.ret_type	= RET_INTEGER,
1148 	.arg1_type	= ARG_PTR_TO_CTX,
1149 };
1150 
BPF_CALL_3(bpf_get_branch_snapshot,void *,buf,u32,size,u64,flags)1151 BPF_CALL_3(bpf_get_branch_snapshot, void *, buf, u32, size, u64, flags)
1152 {
1153 #ifndef CONFIG_X86
1154 	return -ENOENT;
1155 #else
1156 	static const u32 br_entry_size = sizeof(struct perf_branch_entry);
1157 	u32 entry_cnt = size / br_entry_size;
1158 
1159 	entry_cnt = static_call(perf_snapshot_branch_stack)(buf, entry_cnt);
1160 
1161 	if (unlikely(flags))
1162 		return -EINVAL;
1163 
1164 	if (!entry_cnt)
1165 		return -ENOENT;
1166 
1167 	return entry_cnt * br_entry_size;
1168 #endif
1169 }
1170 
1171 static const struct bpf_func_proto bpf_get_branch_snapshot_proto = {
1172 	.func		= bpf_get_branch_snapshot,
1173 	.gpl_only	= true,
1174 	.ret_type	= RET_INTEGER,
1175 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
1176 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
1177 };
1178 
BPF_CALL_3(get_func_arg,void *,ctx,u32,n,u64 *,value)1179 BPF_CALL_3(get_func_arg, void *, ctx, u32, n, u64 *, value)
1180 {
1181 	/* This helper call is inlined by verifier. */
1182 	u64 nr_args = ((u64 *)ctx)[-1];
1183 
1184 	if ((u64) n >= nr_args)
1185 		return -EINVAL;
1186 	*value = ((u64 *)ctx)[n];
1187 	return 0;
1188 }
1189 
1190 static const struct bpf_func_proto bpf_get_func_arg_proto = {
1191 	.func		= get_func_arg,
1192 	.ret_type	= RET_INTEGER,
1193 	.arg1_type	= ARG_PTR_TO_CTX,
1194 	.arg2_type	= ARG_ANYTHING,
1195 	.arg3_type	= ARG_PTR_TO_LONG,
1196 };
1197 
BPF_CALL_2(get_func_ret,void *,ctx,u64 *,value)1198 BPF_CALL_2(get_func_ret, void *, ctx, u64 *, value)
1199 {
1200 	/* This helper call is inlined by verifier. */
1201 	u64 nr_args = ((u64 *)ctx)[-1];
1202 
1203 	*value = ((u64 *)ctx)[nr_args];
1204 	return 0;
1205 }
1206 
1207 static const struct bpf_func_proto bpf_get_func_ret_proto = {
1208 	.func		= get_func_ret,
1209 	.ret_type	= RET_INTEGER,
1210 	.arg1_type	= ARG_PTR_TO_CTX,
1211 	.arg2_type	= ARG_PTR_TO_LONG,
1212 };
1213 
BPF_CALL_1(get_func_arg_cnt,void *,ctx)1214 BPF_CALL_1(get_func_arg_cnt, void *, ctx)
1215 {
1216 	/* This helper call is inlined by verifier. */
1217 	return ((u64 *)ctx)[-1];
1218 }
1219 
1220 static const struct bpf_func_proto bpf_get_func_arg_cnt_proto = {
1221 	.func		= get_func_arg_cnt,
1222 	.ret_type	= RET_INTEGER,
1223 	.arg1_type	= ARG_PTR_TO_CTX,
1224 };
1225 
1226 #ifdef CONFIG_KEYS
1227 __diag_push();
1228 __diag_ignore_all("-Wmissing-prototypes",
1229 		  "kfuncs which will be used in BPF programs");
1230 
1231 /**
1232  * bpf_lookup_user_key - lookup a key by its serial
1233  * @serial: key handle serial number
1234  * @flags: lookup-specific flags
1235  *
1236  * Search a key with a given *serial* and the provided *flags*.
1237  * If found, increment the reference count of the key by one, and
1238  * return it in the bpf_key structure.
1239  *
1240  * The bpf_key structure must be passed to bpf_key_put() when done
1241  * with it, so that the key reference count is decremented and the
1242  * bpf_key structure is freed.
1243  *
1244  * Permission checks are deferred to the time the key is used by
1245  * one of the available key-specific kfuncs.
1246  *
1247  * Set *flags* with KEY_LOOKUP_CREATE, to attempt creating a requested
1248  * special keyring (e.g. session keyring), if it doesn't yet exist.
1249  * Set *flags* with KEY_LOOKUP_PARTIAL, to lookup a key without waiting
1250  * for the key construction, and to retrieve uninstantiated keys (keys
1251  * without data attached to them).
1252  *
1253  * Return: a bpf_key pointer with a valid key pointer if the key is found, a
1254  *         NULL pointer otherwise.
1255  */
bpf_lookup_user_key(u32 serial,u64 flags)1256 struct bpf_key *bpf_lookup_user_key(u32 serial, u64 flags)
1257 {
1258 	key_ref_t key_ref;
1259 	struct bpf_key *bkey;
1260 
1261 	if (flags & ~KEY_LOOKUP_ALL)
1262 		return NULL;
1263 
1264 	/*
1265 	 * Permission check is deferred until the key is used, as the
1266 	 * intent of the caller is unknown here.
1267 	 */
1268 	key_ref = lookup_user_key(serial, flags, KEY_DEFER_PERM_CHECK);
1269 	if (IS_ERR(key_ref))
1270 		return NULL;
1271 
1272 	bkey = kmalloc(sizeof(*bkey), GFP_KERNEL);
1273 	if (!bkey) {
1274 		key_put(key_ref_to_ptr(key_ref));
1275 		return NULL;
1276 	}
1277 
1278 	bkey->key = key_ref_to_ptr(key_ref);
1279 	bkey->has_ref = true;
1280 
1281 	return bkey;
1282 }
1283 
1284 /**
1285  * bpf_lookup_system_key - lookup a key by a system-defined ID
1286  * @id: key ID
1287  *
1288  * Obtain a bpf_key structure with a key pointer set to the passed key ID.
1289  * The key pointer is marked as invalid, to prevent bpf_key_put() from
1290  * attempting to decrement the key reference count on that pointer. The key
1291  * pointer set in such way is currently understood only by
1292  * verify_pkcs7_signature().
1293  *
1294  * Set *id* to one of the values defined in include/linux/verification.h:
1295  * 0 for the primary keyring (immutable keyring of system keys);
1296  * VERIFY_USE_SECONDARY_KEYRING for both the primary and secondary keyring
1297  * (where keys can be added only if they are vouched for by existing keys
1298  * in those keyrings); VERIFY_USE_PLATFORM_KEYRING for the platform
1299  * keyring (primarily used by the integrity subsystem to verify a kexec'ed
1300  * kerned image and, possibly, the initramfs signature).
1301  *
1302  * Return: a bpf_key pointer with an invalid key pointer set from the
1303  *         pre-determined ID on success, a NULL pointer otherwise
1304  */
bpf_lookup_system_key(u64 id)1305 struct bpf_key *bpf_lookup_system_key(u64 id)
1306 {
1307 	struct bpf_key *bkey;
1308 
1309 	if (system_keyring_id_check(id) < 0)
1310 		return NULL;
1311 
1312 	bkey = kmalloc(sizeof(*bkey), GFP_ATOMIC);
1313 	if (!bkey)
1314 		return NULL;
1315 
1316 	bkey->key = (struct key *)(unsigned long)id;
1317 	bkey->has_ref = false;
1318 
1319 	return bkey;
1320 }
1321 
1322 /**
1323  * bpf_key_put - decrement key reference count if key is valid and free bpf_key
1324  * @bkey: bpf_key structure
1325  *
1326  * Decrement the reference count of the key inside *bkey*, if the pointer
1327  * is valid, and free *bkey*.
1328  */
bpf_key_put(struct bpf_key * bkey)1329 void bpf_key_put(struct bpf_key *bkey)
1330 {
1331 	if (bkey->has_ref)
1332 		key_put(bkey->key);
1333 
1334 	kfree(bkey);
1335 }
1336 
1337 #ifdef CONFIG_SYSTEM_DATA_VERIFICATION
1338 /**
1339  * bpf_verify_pkcs7_signature - verify a PKCS#7 signature
1340  * @data_ptr: data to verify
1341  * @sig_ptr: signature of the data
1342  * @trusted_keyring: keyring with keys trusted for signature verification
1343  *
1344  * Verify the PKCS#7 signature *sig_ptr* against the supplied *data_ptr*
1345  * with keys in a keyring referenced by *trusted_keyring*.
1346  *
1347  * Return: 0 on success, a negative value on error.
1348  */
bpf_verify_pkcs7_signature(struct bpf_dynptr_kern * data_ptr,struct bpf_dynptr_kern * sig_ptr,struct bpf_key * trusted_keyring)1349 int bpf_verify_pkcs7_signature(struct bpf_dynptr_kern *data_ptr,
1350 			       struct bpf_dynptr_kern *sig_ptr,
1351 			       struct bpf_key *trusted_keyring)
1352 {
1353 	int ret;
1354 
1355 	if (trusted_keyring->has_ref) {
1356 		/*
1357 		 * Do the permission check deferred in bpf_lookup_user_key().
1358 		 * See bpf_lookup_user_key() for more details.
1359 		 *
1360 		 * A call to key_task_permission() here would be redundant, as
1361 		 * it is already done by keyring_search() called by
1362 		 * find_asymmetric_key().
1363 		 */
1364 		ret = key_validate(trusted_keyring->key);
1365 		if (ret < 0)
1366 			return ret;
1367 	}
1368 
1369 	return verify_pkcs7_signature(data_ptr->data,
1370 				      bpf_dynptr_get_size(data_ptr),
1371 				      sig_ptr->data,
1372 				      bpf_dynptr_get_size(sig_ptr),
1373 				      trusted_keyring->key,
1374 				      VERIFYING_UNSPECIFIED_SIGNATURE, NULL,
1375 				      NULL);
1376 }
1377 #endif /* CONFIG_SYSTEM_DATA_VERIFICATION */
1378 
1379 __diag_pop();
1380 
1381 BTF_SET8_START(key_sig_kfunc_set)
1382 BTF_ID_FLAGS(func, bpf_lookup_user_key, KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE)
1383 BTF_ID_FLAGS(func, bpf_lookup_system_key, KF_ACQUIRE | KF_RET_NULL)
1384 BTF_ID_FLAGS(func, bpf_key_put, KF_RELEASE)
1385 #ifdef CONFIG_SYSTEM_DATA_VERIFICATION
1386 BTF_ID_FLAGS(func, bpf_verify_pkcs7_signature, KF_SLEEPABLE)
1387 #endif
1388 BTF_SET8_END(key_sig_kfunc_set)
1389 
1390 static const struct btf_kfunc_id_set bpf_key_sig_kfunc_set = {
1391 	.owner = THIS_MODULE,
1392 	.set = &key_sig_kfunc_set,
1393 };
1394 
bpf_key_sig_kfuncs_init(void)1395 static int __init bpf_key_sig_kfuncs_init(void)
1396 {
1397 	return register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
1398 					 &bpf_key_sig_kfunc_set);
1399 }
1400 
1401 late_initcall(bpf_key_sig_kfuncs_init);
1402 #endif /* CONFIG_KEYS */
1403 
1404 static const struct bpf_func_proto *
bpf_tracing_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)1405 bpf_tracing_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1406 {
1407 	switch (func_id) {
1408 	case BPF_FUNC_map_lookup_elem:
1409 		return &bpf_map_lookup_elem_proto;
1410 	case BPF_FUNC_map_update_elem:
1411 		return &bpf_map_update_elem_proto;
1412 	case BPF_FUNC_map_delete_elem:
1413 		return &bpf_map_delete_elem_proto;
1414 	case BPF_FUNC_map_push_elem:
1415 		return &bpf_map_push_elem_proto;
1416 	case BPF_FUNC_map_pop_elem:
1417 		return &bpf_map_pop_elem_proto;
1418 	case BPF_FUNC_map_peek_elem:
1419 		return &bpf_map_peek_elem_proto;
1420 	case BPF_FUNC_map_lookup_percpu_elem:
1421 		return &bpf_map_lookup_percpu_elem_proto;
1422 	case BPF_FUNC_ktime_get_ns:
1423 		return &bpf_ktime_get_ns_proto;
1424 	case BPF_FUNC_ktime_get_boot_ns:
1425 		return &bpf_ktime_get_boot_ns_proto;
1426 	case BPF_FUNC_tail_call:
1427 		return &bpf_tail_call_proto;
1428 	case BPF_FUNC_get_current_pid_tgid:
1429 		return &bpf_get_current_pid_tgid_proto;
1430 	case BPF_FUNC_get_current_task:
1431 		return &bpf_get_current_task_proto;
1432 	case BPF_FUNC_get_current_task_btf:
1433 		return &bpf_get_current_task_btf_proto;
1434 	case BPF_FUNC_task_pt_regs:
1435 		return &bpf_task_pt_regs_proto;
1436 	case BPF_FUNC_get_current_uid_gid:
1437 		return &bpf_get_current_uid_gid_proto;
1438 	case BPF_FUNC_get_current_comm:
1439 		return &bpf_get_current_comm_proto;
1440 	case BPF_FUNC_trace_printk:
1441 		return bpf_get_trace_printk_proto();
1442 	case BPF_FUNC_get_smp_processor_id:
1443 		return &bpf_get_smp_processor_id_proto;
1444 	case BPF_FUNC_get_numa_node_id:
1445 		return &bpf_get_numa_node_id_proto;
1446 	case BPF_FUNC_perf_event_read:
1447 		return &bpf_perf_event_read_proto;
1448 	case BPF_FUNC_current_task_under_cgroup:
1449 		return &bpf_current_task_under_cgroup_proto;
1450 	case BPF_FUNC_get_prandom_u32:
1451 		return &bpf_get_prandom_u32_proto;
1452 	case BPF_FUNC_probe_write_user:
1453 		return security_locked_down(LOCKDOWN_BPF_WRITE_USER) < 0 ?
1454 		       NULL : bpf_get_probe_write_proto();
1455 	case BPF_FUNC_probe_read_user:
1456 		return &bpf_probe_read_user_proto;
1457 	case BPF_FUNC_probe_read_kernel:
1458 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1459 		       NULL : &bpf_probe_read_kernel_proto;
1460 	case BPF_FUNC_probe_read_user_str:
1461 		return &bpf_probe_read_user_str_proto;
1462 	case BPF_FUNC_probe_read_kernel_str:
1463 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1464 		       NULL : &bpf_probe_read_kernel_str_proto;
1465 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
1466 	case BPF_FUNC_probe_read:
1467 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1468 		       NULL : &bpf_probe_read_compat_proto;
1469 	case BPF_FUNC_probe_read_str:
1470 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1471 		       NULL : &bpf_probe_read_compat_str_proto;
1472 #endif
1473 #ifdef CONFIG_CGROUPS
1474 	case BPF_FUNC_get_current_cgroup_id:
1475 		return &bpf_get_current_cgroup_id_proto;
1476 	case BPF_FUNC_get_current_ancestor_cgroup_id:
1477 		return &bpf_get_current_ancestor_cgroup_id_proto;
1478 #endif
1479 	case BPF_FUNC_send_signal:
1480 		return &bpf_send_signal_proto;
1481 	case BPF_FUNC_send_signal_thread:
1482 		return &bpf_send_signal_thread_proto;
1483 	case BPF_FUNC_perf_event_read_value:
1484 		return &bpf_perf_event_read_value_proto;
1485 	case BPF_FUNC_get_ns_current_pid_tgid:
1486 		return &bpf_get_ns_current_pid_tgid_proto;
1487 	case BPF_FUNC_ringbuf_output:
1488 		return &bpf_ringbuf_output_proto;
1489 	case BPF_FUNC_ringbuf_reserve:
1490 		return &bpf_ringbuf_reserve_proto;
1491 	case BPF_FUNC_ringbuf_submit:
1492 		return &bpf_ringbuf_submit_proto;
1493 	case BPF_FUNC_ringbuf_discard:
1494 		return &bpf_ringbuf_discard_proto;
1495 	case BPF_FUNC_ringbuf_query:
1496 		return &bpf_ringbuf_query_proto;
1497 	case BPF_FUNC_jiffies64:
1498 		return &bpf_jiffies64_proto;
1499 	case BPF_FUNC_get_task_stack:
1500 		return &bpf_get_task_stack_proto;
1501 	case BPF_FUNC_copy_from_user:
1502 		return prog->aux->sleepable ? &bpf_copy_from_user_proto : NULL;
1503 	case BPF_FUNC_copy_from_user_task:
1504 		return prog->aux->sleepable ? &bpf_copy_from_user_task_proto : NULL;
1505 	case BPF_FUNC_snprintf_btf:
1506 		return &bpf_snprintf_btf_proto;
1507 	case BPF_FUNC_per_cpu_ptr:
1508 		return &bpf_per_cpu_ptr_proto;
1509 	case BPF_FUNC_this_cpu_ptr:
1510 		return &bpf_this_cpu_ptr_proto;
1511 	case BPF_FUNC_task_storage_get:
1512 		return &bpf_task_storage_get_proto;
1513 	case BPF_FUNC_task_storage_delete:
1514 		return &bpf_task_storage_delete_proto;
1515 	case BPF_FUNC_for_each_map_elem:
1516 		return &bpf_for_each_map_elem_proto;
1517 	case BPF_FUNC_snprintf:
1518 		return &bpf_snprintf_proto;
1519 	case BPF_FUNC_get_func_ip:
1520 		return &bpf_get_func_ip_proto_tracing;
1521 	case BPF_FUNC_get_branch_snapshot:
1522 		return &bpf_get_branch_snapshot_proto;
1523 	case BPF_FUNC_find_vma:
1524 		return &bpf_find_vma_proto;
1525 	case BPF_FUNC_trace_vprintk:
1526 		return bpf_get_trace_vprintk_proto();
1527 	default:
1528 		return bpf_base_func_proto(func_id);
1529 	}
1530 }
1531 
1532 static const struct bpf_func_proto *
kprobe_prog_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)1533 kprobe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1534 {
1535 	switch (func_id) {
1536 	case BPF_FUNC_perf_event_output:
1537 		return &bpf_perf_event_output_proto;
1538 	case BPF_FUNC_get_stackid:
1539 		return &bpf_get_stackid_proto;
1540 	case BPF_FUNC_get_stack:
1541 		return &bpf_get_stack_proto;
1542 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
1543 	case BPF_FUNC_override_return:
1544 		return &bpf_override_return_proto;
1545 #endif
1546 	case BPF_FUNC_get_func_ip:
1547 		return prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI ?
1548 			&bpf_get_func_ip_proto_kprobe_multi :
1549 			&bpf_get_func_ip_proto_kprobe;
1550 	case BPF_FUNC_get_attach_cookie:
1551 		return prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI ?
1552 			&bpf_get_attach_cookie_proto_kmulti :
1553 			&bpf_get_attach_cookie_proto_trace;
1554 	default:
1555 		return bpf_tracing_func_proto(func_id, prog);
1556 	}
1557 }
1558 
1559 /* 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)1560 static bool kprobe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1561 					const struct bpf_prog *prog,
1562 					struct bpf_insn_access_aux *info)
1563 {
1564 	if (off < 0 || off >= sizeof(struct pt_regs))
1565 		return false;
1566 	if (type != BPF_READ)
1567 		return false;
1568 	if (off % size != 0)
1569 		return false;
1570 	/*
1571 	 * Assertion for 32 bit to make sure last 8 byte access
1572 	 * (BPF_DW) to the last 4 byte member is disallowed.
1573 	 */
1574 	if (off + size > sizeof(struct pt_regs))
1575 		return false;
1576 
1577 	return true;
1578 }
1579 
1580 const struct bpf_verifier_ops kprobe_verifier_ops = {
1581 	.get_func_proto  = kprobe_prog_func_proto,
1582 	.is_valid_access = kprobe_prog_is_valid_access,
1583 };
1584 
1585 const struct bpf_prog_ops kprobe_prog_ops = {
1586 };
1587 
BPF_CALL_5(bpf_perf_event_output_tp,void *,tp_buff,struct bpf_map *,map,u64,flags,void *,data,u64,size)1588 BPF_CALL_5(bpf_perf_event_output_tp, void *, tp_buff, struct bpf_map *, map,
1589 	   u64, flags, void *, data, u64, size)
1590 {
1591 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1592 
1593 	/*
1594 	 * r1 points to perf tracepoint buffer where first 8 bytes are hidden
1595 	 * from bpf program and contain a pointer to 'struct pt_regs'. Fetch it
1596 	 * from there and call the same bpf_perf_event_output() helper inline.
1597 	 */
1598 	return ____bpf_perf_event_output(regs, map, flags, data, size);
1599 }
1600 
1601 static const struct bpf_func_proto bpf_perf_event_output_proto_tp = {
1602 	.func		= bpf_perf_event_output_tp,
1603 	.gpl_only	= true,
1604 	.ret_type	= RET_INTEGER,
1605 	.arg1_type	= ARG_PTR_TO_CTX,
1606 	.arg2_type	= ARG_CONST_MAP_PTR,
1607 	.arg3_type	= ARG_ANYTHING,
1608 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1609 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
1610 };
1611 
BPF_CALL_3(bpf_get_stackid_tp,void *,tp_buff,struct bpf_map *,map,u64,flags)1612 BPF_CALL_3(bpf_get_stackid_tp, void *, tp_buff, struct bpf_map *, map,
1613 	   u64, flags)
1614 {
1615 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1616 
1617 	/*
1618 	 * Same comment as in bpf_perf_event_output_tp(), only that this time
1619 	 * the other helper's function body cannot be inlined due to being
1620 	 * external, thus we need to call raw helper function.
1621 	 */
1622 	return bpf_get_stackid((unsigned long) regs, (unsigned long) map,
1623 			       flags, 0, 0);
1624 }
1625 
1626 static const struct bpf_func_proto bpf_get_stackid_proto_tp = {
1627 	.func		= bpf_get_stackid_tp,
1628 	.gpl_only	= true,
1629 	.ret_type	= RET_INTEGER,
1630 	.arg1_type	= ARG_PTR_TO_CTX,
1631 	.arg2_type	= ARG_CONST_MAP_PTR,
1632 	.arg3_type	= ARG_ANYTHING,
1633 };
1634 
BPF_CALL_4(bpf_get_stack_tp,void *,tp_buff,void *,buf,u32,size,u64,flags)1635 BPF_CALL_4(bpf_get_stack_tp, void *, tp_buff, void *, buf, u32, size,
1636 	   u64, flags)
1637 {
1638 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1639 
1640 	return bpf_get_stack((unsigned long) regs, (unsigned long) buf,
1641 			     (unsigned long) size, flags, 0);
1642 }
1643 
1644 static const struct bpf_func_proto bpf_get_stack_proto_tp = {
1645 	.func		= bpf_get_stack_tp,
1646 	.gpl_only	= true,
1647 	.ret_type	= RET_INTEGER,
1648 	.arg1_type	= ARG_PTR_TO_CTX,
1649 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
1650 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
1651 	.arg4_type	= ARG_ANYTHING,
1652 };
1653 
1654 static const struct bpf_func_proto *
tp_prog_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)1655 tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1656 {
1657 	switch (func_id) {
1658 	case BPF_FUNC_perf_event_output:
1659 		return &bpf_perf_event_output_proto_tp;
1660 	case BPF_FUNC_get_stackid:
1661 		return &bpf_get_stackid_proto_tp;
1662 	case BPF_FUNC_get_stack:
1663 		return &bpf_get_stack_proto_tp;
1664 	case BPF_FUNC_get_attach_cookie:
1665 		return &bpf_get_attach_cookie_proto_trace;
1666 	default:
1667 		return bpf_tracing_func_proto(func_id, prog);
1668 	}
1669 }
1670 
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)1671 static bool tp_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1672 				    const struct bpf_prog *prog,
1673 				    struct bpf_insn_access_aux *info)
1674 {
1675 	if (off < sizeof(void *) || off >= PERF_MAX_TRACE_SIZE)
1676 		return false;
1677 	if (type != BPF_READ)
1678 		return false;
1679 	if (off % size != 0)
1680 		return false;
1681 
1682 	BUILD_BUG_ON(PERF_MAX_TRACE_SIZE % sizeof(__u64));
1683 	return true;
1684 }
1685 
1686 const struct bpf_verifier_ops tracepoint_verifier_ops = {
1687 	.get_func_proto  = tp_prog_func_proto,
1688 	.is_valid_access = tp_prog_is_valid_access,
1689 };
1690 
1691 const struct bpf_prog_ops tracepoint_prog_ops = {
1692 };
1693 
BPF_CALL_3(bpf_perf_prog_read_value,struct bpf_perf_event_data_kern *,ctx,struct bpf_perf_event_value *,buf,u32,size)1694 BPF_CALL_3(bpf_perf_prog_read_value, struct bpf_perf_event_data_kern *, ctx,
1695 	   struct bpf_perf_event_value *, buf, u32, size)
1696 {
1697 	int err = -EINVAL;
1698 
1699 	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
1700 		goto clear;
1701 	err = perf_event_read_local(ctx->event, &buf->counter, &buf->enabled,
1702 				    &buf->running);
1703 	if (unlikely(err))
1704 		goto clear;
1705 	return 0;
1706 clear:
1707 	memset(buf, 0, size);
1708 	return err;
1709 }
1710 
1711 static const struct bpf_func_proto bpf_perf_prog_read_value_proto = {
1712          .func           = bpf_perf_prog_read_value,
1713          .gpl_only       = true,
1714          .ret_type       = RET_INTEGER,
1715          .arg1_type      = ARG_PTR_TO_CTX,
1716          .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
1717          .arg3_type      = ARG_CONST_SIZE,
1718 };
1719 
BPF_CALL_4(bpf_read_branch_records,struct bpf_perf_event_data_kern *,ctx,void *,buf,u32,size,u64,flags)1720 BPF_CALL_4(bpf_read_branch_records, struct bpf_perf_event_data_kern *, ctx,
1721 	   void *, buf, u32, size, u64, flags)
1722 {
1723 	static const u32 br_entry_size = sizeof(struct perf_branch_entry);
1724 	struct perf_branch_stack *br_stack = ctx->data->br_stack;
1725 	u32 to_copy;
1726 
1727 	if (unlikely(flags & ~BPF_F_GET_BRANCH_RECORDS_SIZE))
1728 		return -EINVAL;
1729 
1730 	if (unlikely(!(ctx->data->sample_flags & PERF_SAMPLE_BRANCH_STACK)))
1731 		return -ENOENT;
1732 
1733 	if (unlikely(!br_stack))
1734 		return -ENOENT;
1735 
1736 	if (flags & BPF_F_GET_BRANCH_RECORDS_SIZE)
1737 		return br_stack->nr * br_entry_size;
1738 
1739 	if (!buf || (size % br_entry_size != 0))
1740 		return -EINVAL;
1741 
1742 	to_copy = min_t(u32, br_stack->nr * br_entry_size, size);
1743 	memcpy(buf, br_stack->entries, to_copy);
1744 
1745 	return to_copy;
1746 }
1747 
1748 static const struct bpf_func_proto bpf_read_branch_records_proto = {
1749 	.func           = bpf_read_branch_records,
1750 	.gpl_only       = true,
1751 	.ret_type       = RET_INTEGER,
1752 	.arg1_type      = ARG_PTR_TO_CTX,
1753 	.arg2_type      = ARG_PTR_TO_MEM_OR_NULL,
1754 	.arg3_type      = ARG_CONST_SIZE_OR_ZERO,
1755 	.arg4_type      = ARG_ANYTHING,
1756 };
1757 
1758 static const struct bpf_func_proto *
pe_prog_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)1759 pe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1760 {
1761 	switch (func_id) {
1762 	case BPF_FUNC_perf_event_output:
1763 		return &bpf_perf_event_output_proto_tp;
1764 	case BPF_FUNC_get_stackid:
1765 		return &bpf_get_stackid_proto_pe;
1766 	case BPF_FUNC_get_stack:
1767 		return &bpf_get_stack_proto_pe;
1768 	case BPF_FUNC_perf_prog_read_value:
1769 		return &bpf_perf_prog_read_value_proto;
1770 	case BPF_FUNC_read_branch_records:
1771 		return &bpf_read_branch_records_proto;
1772 	case BPF_FUNC_get_attach_cookie:
1773 		return &bpf_get_attach_cookie_proto_pe;
1774 	default:
1775 		return bpf_tracing_func_proto(func_id, prog);
1776 	}
1777 }
1778 
1779 /*
1780  * bpf_raw_tp_regs are separate from bpf_pt_regs used from skb/xdp
1781  * to avoid potential recursive reuse issue when/if tracepoints are added
1782  * inside bpf_*_event_output, bpf_get_stackid and/or bpf_get_stack.
1783  *
1784  * Since raw tracepoints run despite bpf_prog_active, support concurrent usage
1785  * in normal, irq, and nmi context.
1786  */
1787 struct bpf_raw_tp_regs {
1788 	struct pt_regs regs[3];
1789 };
1790 static DEFINE_PER_CPU(struct bpf_raw_tp_regs, bpf_raw_tp_regs);
1791 static DEFINE_PER_CPU(int, bpf_raw_tp_nest_level);
get_bpf_raw_tp_regs(void)1792 static struct pt_regs *get_bpf_raw_tp_regs(void)
1793 {
1794 	struct bpf_raw_tp_regs *tp_regs = this_cpu_ptr(&bpf_raw_tp_regs);
1795 	int nest_level = this_cpu_inc_return(bpf_raw_tp_nest_level);
1796 
1797 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(tp_regs->regs))) {
1798 		this_cpu_dec(bpf_raw_tp_nest_level);
1799 		return ERR_PTR(-EBUSY);
1800 	}
1801 
1802 	return &tp_regs->regs[nest_level - 1];
1803 }
1804 
put_bpf_raw_tp_regs(void)1805 static void put_bpf_raw_tp_regs(void)
1806 {
1807 	this_cpu_dec(bpf_raw_tp_nest_level);
1808 }
1809 
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)1810 BPF_CALL_5(bpf_perf_event_output_raw_tp, struct bpf_raw_tracepoint_args *, args,
1811 	   struct bpf_map *, map, u64, flags, void *, data, u64, size)
1812 {
1813 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1814 	int ret;
1815 
1816 	if (IS_ERR(regs))
1817 		return PTR_ERR(regs);
1818 
1819 	perf_fetch_caller_regs(regs);
1820 	ret = ____bpf_perf_event_output(regs, map, flags, data, size);
1821 
1822 	put_bpf_raw_tp_regs();
1823 	return ret;
1824 }
1825 
1826 static const struct bpf_func_proto bpf_perf_event_output_proto_raw_tp = {
1827 	.func		= bpf_perf_event_output_raw_tp,
1828 	.gpl_only	= true,
1829 	.ret_type	= RET_INTEGER,
1830 	.arg1_type	= ARG_PTR_TO_CTX,
1831 	.arg2_type	= ARG_CONST_MAP_PTR,
1832 	.arg3_type	= ARG_ANYTHING,
1833 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1834 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
1835 };
1836 
1837 extern const struct bpf_func_proto bpf_skb_output_proto;
1838 extern const struct bpf_func_proto bpf_xdp_output_proto;
1839 extern const struct bpf_func_proto bpf_xdp_get_buff_len_trace_proto;
1840 
BPF_CALL_3(bpf_get_stackid_raw_tp,struct bpf_raw_tracepoint_args *,args,struct bpf_map *,map,u64,flags)1841 BPF_CALL_3(bpf_get_stackid_raw_tp, struct bpf_raw_tracepoint_args *, args,
1842 	   struct bpf_map *, map, u64, flags)
1843 {
1844 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1845 	int ret;
1846 
1847 	if (IS_ERR(regs))
1848 		return PTR_ERR(regs);
1849 
1850 	perf_fetch_caller_regs(regs);
1851 	/* similar to bpf_perf_event_output_tp, but pt_regs fetched differently */
1852 	ret = bpf_get_stackid((unsigned long) regs, (unsigned long) map,
1853 			      flags, 0, 0);
1854 	put_bpf_raw_tp_regs();
1855 	return ret;
1856 }
1857 
1858 static const struct bpf_func_proto bpf_get_stackid_proto_raw_tp = {
1859 	.func		= bpf_get_stackid_raw_tp,
1860 	.gpl_only	= true,
1861 	.ret_type	= RET_INTEGER,
1862 	.arg1_type	= ARG_PTR_TO_CTX,
1863 	.arg2_type	= ARG_CONST_MAP_PTR,
1864 	.arg3_type	= ARG_ANYTHING,
1865 };
1866 
BPF_CALL_4(bpf_get_stack_raw_tp,struct bpf_raw_tracepoint_args *,args,void *,buf,u32,size,u64,flags)1867 BPF_CALL_4(bpf_get_stack_raw_tp, struct bpf_raw_tracepoint_args *, args,
1868 	   void *, buf, u32, size, u64, flags)
1869 {
1870 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1871 	int ret;
1872 
1873 	if (IS_ERR(regs))
1874 		return PTR_ERR(regs);
1875 
1876 	perf_fetch_caller_regs(regs);
1877 	ret = bpf_get_stack((unsigned long) regs, (unsigned long) buf,
1878 			    (unsigned long) size, flags, 0);
1879 	put_bpf_raw_tp_regs();
1880 	return ret;
1881 }
1882 
1883 static const struct bpf_func_proto bpf_get_stack_proto_raw_tp = {
1884 	.func		= bpf_get_stack_raw_tp,
1885 	.gpl_only	= true,
1886 	.ret_type	= RET_INTEGER,
1887 	.arg1_type	= ARG_PTR_TO_CTX,
1888 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1889 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
1890 	.arg4_type	= ARG_ANYTHING,
1891 };
1892 
1893 static const struct bpf_func_proto *
raw_tp_prog_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)1894 raw_tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1895 {
1896 	switch (func_id) {
1897 	case BPF_FUNC_perf_event_output:
1898 		return &bpf_perf_event_output_proto_raw_tp;
1899 	case BPF_FUNC_get_stackid:
1900 		return &bpf_get_stackid_proto_raw_tp;
1901 	case BPF_FUNC_get_stack:
1902 		return &bpf_get_stack_proto_raw_tp;
1903 	default:
1904 		return bpf_tracing_func_proto(func_id, prog);
1905 	}
1906 }
1907 
1908 const struct bpf_func_proto *
tracing_prog_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)1909 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1910 {
1911 	const struct bpf_func_proto *fn;
1912 
1913 	switch (func_id) {
1914 #ifdef CONFIG_NET
1915 	case BPF_FUNC_skb_output:
1916 		return &bpf_skb_output_proto;
1917 	case BPF_FUNC_xdp_output:
1918 		return &bpf_xdp_output_proto;
1919 	case BPF_FUNC_skc_to_tcp6_sock:
1920 		return &bpf_skc_to_tcp6_sock_proto;
1921 	case BPF_FUNC_skc_to_tcp_sock:
1922 		return &bpf_skc_to_tcp_sock_proto;
1923 	case BPF_FUNC_skc_to_tcp_timewait_sock:
1924 		return &bpf_skc_to_tcp_timewait_sock_proto;
1925 	case BPF_FUNC_skc_to_tcp_request_sock:
1926 		return &bpf_skc_to_tcp_request_sock_proto;
1927 	case BPF_FUNC_skc_to_udp6_sock:
1928 		return &bpf_skc_to_udp6_sock_proto;
1929 	case BPF_FUNC_skc_to_unix_sock:
1930 		return &bpf_skc_to_unix_sock_proto;
1931 	case BPF_FUNC_skc_to_mptcp_sock:
1932 		return &bpf_skc_to_mptcp_sock_proto;
1933 	case BPF_FUNC_sk_storage_get:
1934 		return &bpf_sk_storage_get_tracing_proto;
1935 	case BPF_FUNC_sk_storage_delete:
1936 		return &bpf_sk_storage_delete_tracing_proto;
1937 	case BPF_FUNC_sock_from_file:
1938 		return &bpf_sock_from_file_proto;
1939 	case BPF_FUNC_get_socket_cookie:
1940 		return &bpf_get_socket_ptr_cookie_proto;
1941 	case BPF_FUNC_xdp_get_buff_len:
1942 		return &bpf_xdp_get_buff_len_trace_proto;
1943 #endif
1944 	case BPF_FUNC_seq_printf:
1945 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1946 		       &bpf_seq_printf_proto :
1947 		       NULL;
1948 	case BPF_FUNC_seq_write:
1949 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1950 		       &bpf_seq_write_proto :
1951 		       NULL;
1952 	case BPF_FUNC_seq_printf_btf:
1953 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1954 		       &bpf_seq_printf_btf_proto :
1955 		       NULL;
1956 	case BPF_FUNC_d_path:
1957 		return &bpf_d_path_proto;
1958 	case BPF_FUNC_get_func_arg:
1959 		return bpf_prog_has_trampoline(prog) ? &bpf_get_func_arg_proto : NULL;
1960 	case BPF_FUNC_get_func_ret:
1961 		return bpf_prog_has_trampoline(prog) ? &bpf_get_func_ret_proto : NULL;
1962 	case BPF_FUNC_get_func_arg_cnt:
1963 		return bpf_prog_has_trampoline(prog) ? &bpf_get_func_arg_cnt_proto : NULL;
1964 	case BPF_FUNC_get_attach_cookie:
1965 		return bpf_prog_has_trampoline(prog) ? &bpf_get_attach_cookie_proto_tracing : NULL;
1966 	default:
1967 		fn = raw_tp_prog_func_proto(func_id, prog);
1968 		if (!fn && prog->expected_attach_type == BPF_TRACE_ITER)
1969 			fn = bpf_iter_get_func_proto(func_id, prog);
1970 		return fn;
1971 	}
1972 }
1973 
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)1974 static bool raw_tp_prog_is_valid_access(int off, int size,
1975 					enum bpf_access_type type,
1976 					const struct bpf_prog *prog,
1977 					struct bpf_insn_access_aux *info)
1978 {
1979 	return bpf_tracing_ctx_access(off, size, type);
1980 }
1981 
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)1982 static bool tracing_prog_is_valid_access(int off, int size,
1983 					 enum bpf_access_type type,
1984 					 const struct bpf_prog *prog,
1985 					 struct bpf_insn_access_aux *info)
1986 {
1987 	return bpf_tracing_btf_ctx_access(off, size, type, prog, info);
1988 }
1989 
bpf_prog_test_run_tracing(struct bpf_prog * prog,const union bpf_attr * kattr,union bpf_attr __user * uattr)1990 int __weak bpf_prog_test_run_tracing(struct bpf_prog *prog,
1991 				     const union bpf_attr *kattr,
1992 				     union bpf_attr __user *uattr)
1993 {
1994 	return -ENOTSUPP;
1995 }
1996 
1997 const struct bpf_verifier_ops raw_tracepoint_verifier_ops = {
1998 	.get_func_proto  = raw_tp_prog_func_proto,
1999 	.is_valid_access = raw_tp_prog_is_valid_access,
2000 };
2001 
2002 const struct bpf_prog_ops raw_tracepoint_prog_ops = {
2003 #ifdef CONFIG_NET
2004 	.test_run = bpf_prog_test_run_raw_tp,
2005 #endif
2006 };
2007 
2008 const struct bpf_verifier_ops tracing_verifier_ops = {
2009 	.get_func_proto  = tracing_prog_func_proto,
2010 	.is_valid_access = tracing_prog_is_valid_access,
2011 };
2012 
2013 const struct bpf_prog_ops tracing_prog_ops = {
2014 	.test_run = bpf_prog_test_run_tracing,
2015 };
2016 
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)2017 static bool raw_tp_writable_prog_is_valid_access(int off, int size,
2018 						 enum bpf_access_type type,
2019 						 const struct bpf_prog *prog,
2020 						 struct bpf_insn_access_aux *info)
2021 {
2022 	if (off == 0) {
2023 		if (size != sizeof(u64) || type != BPF_READ)
2024 			return false;
2025 		info->reg_type = PTR_TO_TP_BUFFER;
2026 	}
2027 	return raw_tp_prog_is_valid_access(off, size, type, prog, info);
2028 }
2029 
2030 const struct bpf_verifier_ops raw_tracepoint_writable_verifier_ops = {
2031 	.get_func_proto  = raw_tp_prog_func_proto,
2032 	.is_valid_access = raw_tp_writable_prog_is_valid_access,
2033 };
2034 
2035 const struct bpf_prog_ops raw_tracepoint_writable_prog_ops = {
2036 };
2037 
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)2038 static bool pe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
2039 				    const struct bpf_prog *prog,
2040 				    struct bpf_insn_access_aux *info)
2041 {
2042 	const int size_u64 = sizeof(u64);
2043 
2044 	if (off < 0 || off >= sizeof(struct bpf_perf_event_data))
2045 		return false;
2046 	if (type != BPF_READ)
2047 		return false;
2048 	if (off % size != 0) {
2049 		if (sizeof(unsigned long) != 4)
2050 			return false;
2051 		if (size != 8)
2052 			return false;
2053 		if (off % size != 4)
2054 			return false;
2055 	}
2056 
2057 	switch (off) {
2058 	case bpf_ctx_range(struct bpf_perf_event_data, sample_period):
2059 		bpf_ctx_record_field_size(info, size_u64);
2060 		if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
2061 			return false;
2062 		break;
2063 	case bpf_ctx_range(struct bpf_perf_event_data, addr):
2064 		bpf_ctx_record_field_size(info, size_u64);
2065 		if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
2066 			return false;
2067 		break;
2068 	default:
2069 		if (size != sizeof(long))
2070 			return false;
2071 	}
2072 
2073 	return true;
2074 }
2075 
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)2076 static u32 pe_prog_convert_ctx_access(enum bpf_access_type type,
2077 				      const struct bpf_insn *si,
2078 				      struct bpf_insn *insn_buf,
2079 				      struct bpf_prog *prog, u32 *target_size)
2080 {
2081 	struct bpf_insn *insn = insn_buf;
2082 
2083 	switch (si->off) {
2084 	case offsetof(struct bpf_perf_event_data, sample_period):
2085 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
2086 						       data), si->dst_reg, si->src_reg,
2087 				      offsetof(struct bpf_perf_event_data_kern, data));
2088 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
2089 				      bpf_target_off(struct perf_sample_data, period, 8,
2090 						     target_size));
2091 		break;
2092 	case offsetof(struct bpf_perf_event_data, addr):
2093 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
2094 						       data), si->dst_reg, si->src_reg,
2095 				      offsetof(struct bpf_perf_event_data_kern, data));
2096 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
2097 				      bpf_target_off(struct perf_sample_data, addr, 8,
2098 						     target_size));
2099 		break;
2100 	default:
2101 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
2102 						       regs), si->dst_reg, si->src_reg,
2103 				      offsetof(struct bpf_perf_event_data_kern, regs));
2104 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(long), si->dst_reg, si->dst_reg,
2105 				      si->off);
2106 		break;
2107 	}
2108 
2109 	return insn - insn_buf;
2110 }
2111 
2112 const struct bpf_verifier_ops perf_event_verifier_ops = {
2113 	.get_func_proto		= pe_prog_func_proto,
2114 	.is_valid_access	= pe_prog_is_valid_access,
2115 	.convert_ctx_access	= pe_prog_convert_ctx_access,
2116 };
2117 
2118 const struct bpf_prog_ops perf_event_prog_ops = {
2119 };
2120 
2121 static DEFINE_MUTEX(bpf_event_mutex);
2122 
2123 #define BPF_TRACE_MAX_PROGS 64
2124 
perf_event_attach_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)2125 int perf_event_attach_bpf_prog(struct perf_event *event,
2126 			       struct bpf_prog *prog,
2127 			       u64 bpf_cookie)
2128 {
2129 	struct bpf_prog_array *old_array;
2130 	struct bpf_prog_array *new_array;
2131 	int ret = -EEXIST;
2132 
2133 	/*
2134 	 * Kprobe override only works if they are on the function entry,
2135 	 * and only if they are on the opt-in list.
2136 	 */
2137 	if (prog->kprobe_override &&
2138 	    (!trace_kprobe_on_func_entry(event->tp_event) ||
2139 	     !trace_kprobe_error_injectable(event->tp_event)))
2140 		return -EINVAL;
2141 
2142 	mutex_lock(&bpf_event_mutex);
2143 
2144 	if (event->prog)
2145 		goto unlock;
2146 
2147 	old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
2148 	if (old_array &&
2149 	    bpf_prog_array_length(old_array) >= BPF_TRACE_MAX_PROGS) {
2150 		ret = -E2BIG;
2151 		goto unlock;
2152 	}
2153 
2154 	ret = bpf_prog_array_copy(old_array, NULL, prog, bpf_cookie, &new_array);
2155 	if (ret < 0)
2156 		goto unlock;
2157 
2158 	/* set the new array to event->tp_event and set event->prog */
2159 	event->prog = prog;
2160 	event->bpf_cookie = bpf_cookie;
2161 	rcu_assign_pointer(event->tp_event->prog_array, new_array);
2162 	bpf_prog_array_free_sleepable(old_array);
2163 
2164 unlock:
2165 	mutex_unlock(&bpf_event_mutex);
2166 	return ret;
2167 }
2168 
perf_event_detach_bpf_prog(struct perf_event * event)2169 void perf_event_detach_bpf_prog(struct perf_event *event)
2170 {
2171 	struct bpf_prog_array *old_array;
2172 	struct bpf_prog_array *new_array;
2173 	int ret;
2174 
2175 	mutex_lock(&bpf_event_mutex);
2176 
2177 	if (!event->prog)
2178 		goto unlock;
2179 
2180 	old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
2181 	ret = bpf_prog_array_copy(old_array, event->prog, NULL, 0, &new_array);
2182 	if (ret == -ENOENT)
2183 		goto unlock;
2184 	if (ret < 0) {
2185 		bpf_prog_array_delete_safe(old_array, event->prog);
2186 	} else {
2187 		rcu_assign_pointer(event->tp_event->prog_array, new_array);
2188 		bpf_prog_array_free_sleepable(old_array);
2189 	}
2190 
2191 	bpf_prog_put(event->prog);
2192 	event->prog = NULL;
2193 
2194 unlock:
2195 	mutex_unlock(&bpf_event_mutex);
2196 }
2197 
perf_event_query_prog_array(struct perf_event * event,void __user * info)2198 int perf_event_query_prog_array(struct perf_event *event, void __user *info)
2199 {
2200 	struct perf_event_query_bpf __user *uquery = info;
2201 	struct perf_event_query_bpf query = {};
2202 	struct bpf_prog_array *progs;
2203 	u32 *ids, prog_cnt, ids_len;
2204 	int ret;
2205 
2206 	if (!perfmon_capable())
2207 		return -EPERM;
2208 	if (event->attr.type != PERF_TYPE_TRACEPOINT)
2209 		return -EINVAL;
2210 	if (copy_from_user(&query, uquery, sizeof(query)))
2211 		return -EFAULT;
2212 
2213 	ids_len = query.ids_len;
2214 	if (ids_len > BPF_TRACE_MAX_PROGS)
2215 		return -E2BIG;
2216 	ids = kcalloc(ids_len, sizeof(u32), GFP_USER | __GFP_NOWARN);
2217 	if (!ids)
2218 		return -ENOMEM;
2219 	/*
2220 	 * The above kcalloc returns ZERO_SIZE_PTR when ids_len = 0, which
2221 	 * is required when user only wants to check for uquery->prog_cnt.
2222 	 * There is no need to check for it since the case is handled
2223 	 * gracefully in bpf_prog_array_copy_info.
2224 	 */
2225 
2226 	mutex_lock(&bpf_event_mutex);
2227 	progs = bpf_event_rcu_dereference(event->tp_event->prog_array);
2228 	ret = bpf_prog_array_copy_info(progs, ids, ids_len, &prog_cnt);
2229 	mutex_unlock(&bpf_event_mutex);
2230 
2231 	if (copy_to_user(&uquery->prog_cnt, &prog_cnt, sizeof(prog_cnt)) ||
2232 	    copy_to_user(uquery->ids, ids, ids_len * sizeof(u32)))
2233 		ret = -EFAULT;
2234 
2235 	kfree(ids);
2236 	return ret;
2237 }
2238 
2239 extern struct bpf_raw_event_map __start__bpf_raw_tp[];
2240 extern struct bpf_raw_event_map __stop__bpf_raw_tp[];
2241 
bpf_get_raw_tracepoint(const char * name)2242 struct bpf_raw_event_map *bpf_get_raw_tracepoint(const char *name)
2243 {
2244 	struct bpf_raw_event_map *btp = __start__bpf_raw_tp;
2245 
2246 	for (; btp < __stop__bpf_raw_tp; btp++) {
2247 		if (!strcmp(btp->tp->name, name))
2248 			return btp;
2249 	}
2250 
2251 	return bpf_get_raw_tracepoint_module(name);
2252 }
2253 
bpf_put_raw_tracepoint(struct bpf_raw_event_map * btp)2254 void bpf_put_raw_tracepoint(struct bpf_raw_event_map *btp)
2255 {
2256 	struct module *mod;
2257 
2258 	preempt_disable();
2259 	mod = __module_address((unsigned long)btp);
2260 	module_put(mod);
2261 	preempt_enable();
2262 }
2263 
2264 static __always_inline
__bpf_trace_run(struct bpf_prog * prog,u64 * args)2265 void __bpf_trace_run(struct bpf_prog *prog, u64 *args)
2266 {
2267 	cant_sleep();
2268 	if (unlikely(this_cpu_inc_return(*(prog->active)) != 1)) {
2269 		bpf_prog_inc_misses_counter(prog);
2270 		goto out;
2271 	}
2272 	rcu_read_lock();
2273 	(void) bpf_prog_run(prog, args);
2274 	rcu_read_unlock();
2275 out:
2276 	this_cpu_dec(*(prog->active));
2277 }
2278 
2279 #define UNPACK(...)			__VA_ARGS__
2280 #define REPEAT_1(FN, DL, X, ...)	FN(X)
2281 #define REPEAT_2(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_1(FN, DL, __VA_ARGS__)
2282 #define REPEAT_3(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_2(FN, DL, __VA_ARGS__)
2283 #define REPEAT_4(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_3(FN, DL, __VA_ARGS__)
2284 #define REPEAT_5(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_4(FN, DL, __VA_ARGS__)
2285 #define REPEAT_6(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_5(FN, DL, __VA_ARGS__)
2286 #define REPEAT_7(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_6(FN, DL, __VA_ARGS__)
2287 #define REPEAT_8(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_7(FN, DL, __VA_ARGS__)
2288 #define REPEAT_9(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_8(FN, DL, __VA_ARGS__)
2289 #define REPEAT_10(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_9(FN, DL, __VA_ARGS__)
2290 #define REPEAT_11(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_10(FN, DL, __VA_ARGS__)
2291 #define REPEAT_12(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_11(FN, DL, __VA_ARGS__)
2292 #define REPEAT(X, FN, DL, ...)		REPEAT_##X(FN, DL, __VA_ARGS__)
2293 
2294 #define SARG(X)		u64 arg##X
2295 #define COPY(X)		args[X] = arg##X
2296 
2297 #define __DL_COM	(,)
2298 #define __DL_SEM	(;)
2299 
2300 #define __SEQ_0_11	0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
2301 
2302 #define BPF_TRACE_DEFN_x(x)						\
2303 	void bpf_trace_run##x(struct bpf_prog *prog,			\
2304 			      REPEAT(x, SARG, __DL_COM, __SEQ_0_11))	\
2305 	{								\
2306 		u64 args[x];						\
2307 		REPEAT(x, COPY, __DL_SEM, __SEQ_0_11);			\
2308 		__bpf_trace_run(prog, args);				\
2309 	}								\
2310 	EXPORT_SYMBOL_GPL(bpf_trace_run##x)
2311 BPF_TRACE_DEFN_x(1);
2312 BPF_TRACE_DEFN_x(2);
2313 BPF_TRACE_DEFN_x(3);
2314 BPF_TRACE_DEFN_x(4);
2315 BPF_TRACE_DEFN_x(5);
2316 BPF_TRACE_DEFN_x(6);
2317 BPF_TRACE_DEFN_x(7);
2318 BPF_TRACE_DEFN_x(8);
2319 BPF_TRACE_DEFN_x(9);
2320 BPF_TRACE_DEFN_x(10);
2321 BPF_TRACE_DEFN_x(11);
2322 BPF_TRACE_DEFN_x(12);
2323 
__bpf_probe_register(struct bpf_raw_event_map * btp,struct bpf_prog * prog)2324 static int __bpf_probe_register(struct bpf_raw_event_map *btp, struct bpf_prog *prog)
2325 {
2326 	struct tracepoint *tp = btp->tp;
2327 
2328 	/*
2329 	 * check that program doesn't access arguments beyond what's
2330 	 * available in this tracepoint
2331 	 */
2332 	if (prog->aux->max_ctx_offset > btp->num_args * sizeof(u64))
2333 		return -EINVAL;
2334 
2335 	if (prog->aux->max_tp_access > btp->writable_size)
2336 		return -EINVAL;
2337 
2338 	return tracepoint_probe_register_may_exist(tp, (void *)btp->bpf_func,
2339 						   prog);
2340 }
2341 
bpf_probe_register(struct bpf_raw_event_map * btp,struct bpf_prog * prog)2342 int bpf_probe_register(struct bpf_raw_event_map *btp, struct bpf_prog *prog)
2343 {
2344 	return __bpf_probe_register(btp, prog);
2345 }
2346 
bpf_probe_unregister(struct bpf_raw_event_map * btp,struct bpf_prog * prog)2347 int bpf_probe_unregister(struct bpf_raw_event_map *btp, struct bpf_prog *prog)
2348 {
2349 	return tracepoint_probe_unregister(btp->tp, (void *)btp->bpf_func, prog);
2350 }
2351 
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)2352 int bpf_get_perf_event_info(const struct perf_event *event, u32 *prog_id,
2353 			    u32 *fd_type, const char **buf,
2354 			    u64 *probe_offset, u64 *probe_addr)
2355 {
2356 	bool is_tracepoint, is_syscall_tp;
2357 	struct bpf_prog *prog;
2358 	int flags, err = 0;
2359 
2360 	prog = event->prog;
2361 	if (!prog)
2362 		return -ENOENT;
2363 
2364 	/* not supporting BPF_PROG_TYPE_PERF_EVENT yet */
2365 	if (prog->type == BPF_PROG_TYPE_PERF_EVENT)
2366 		return -EOPNOTSUPP;
2367 
2368 	*prog_id = prog->aux->id;
2369 	flags = event->tp_event->flags;
2370 	is_tracepoint = flags & TRACE_EVENT_FL_TRACEPOINT;
2371 	is_syscall_tp = is_syscall_trace_event(event->tp_event);
2372 
2373 	if (is_tracepoint || is_syscall_tp) {
2374 		*buf = is_tracepoint ? event->tp_event->tp->name
2375 				     : event->tp_event->name;
2376 		*fd_type = BPF_FD_TYPE_TRACEPOINT;
2377 		*probe_offset = 0x0;
2378 		*probe_addr = 0x0;
2379 	} else {
2380 		/* kprobe/uprobe */
2381 		err = -EOPNOTSUPP;
2382 #ifdef CONFIG_KPROBE_EVENTS
2383 		if (flags & TRACE_EVENT_FL_KPROBE)
2384 			err = bpf_get_kprobe_info(event, fd_type, buf,
2385 						  probe_offset, probe_addr,
2386 						  event->attr.type == PERF_TYPE_TRACEPOINT);
2387 #endif
2388 #ifdef CONFIG_UPROBE_EVENTS
2389 		if (flags & TRACE_EVENT_FL_UPROBE)
2390 			err = bpf_get_uprobe_info(event, fd_type, buf,
2391 						  probe_offset, probe_addr,
2392 						  event->attr.type == PERF_TYPE_TRACEPOINT);
2393 #endif
2394 	}
2395 
2396 	return err;
2397 }
2398 
send_signal_irq_work_init(void)2399 static int __init send_signal_irq_work_init(void)
2400 {
2401 	int cpu;
2402 	struct send_signal_irq_work *work;
2403 
2404 	for_each_possible_cpu(cpu) {
2405 		work = per_cpu_ptr(&send_signal_work, cpu);
2406 		init_irq_work(&work->irq_work, do_bpf_send_signal);
2407 	}
2408 	return 0;
2409 }
2410 
2411 subsys_initcall(send_signal_irq_work_init);
2412 
2413 #ifdef CONFIG_MODULES
bpf_event_notify(struct notifier_block * nb,unsigned long op,void * module)2414 static int bpf_event_notify(struct notifier_block *nb, unsigned long op,
2415 			    void *module)
2416 {
2417 	struct bpf_trace_module *btm, *tmp;
2418 	struct module *mod = module;
2419 	int ret = 0;
2420 
2421 	if (mod->num_bpf_raw_events == 0 ||
2422 	    (op != MODULE_STATE_COMING && op != MODULE_STATE_GOING))
2423 		goto out;
2424 
2425 	mutex_lock(&bpf_module_mutex);
2426 
2427 	switch (op) {
2428 	case MODULE_STATE_COMING:
2429 		btm = kzalloc(sizeof(*btm), GFP_KERNEL);
2430 		if (btm) {
2431 			btm->module = module;
2432 			list_add(&btm->list, &bpf_trace_modules);
2433 		} else {
2434 			ret = -ENOMEM;
2435 		}
2436 		break;
2437 	case MODULE_STATE_GOING:
2438 		list_for_each_entry_safe(btm, tmp, &bpf_trace_modules, list) {
2439 			if (btm->module == module) {
2440 				list_del(&btm->list);
2441 				kfree(btm);
2442 				break;
2443 			}
2444 		}
2445 		break;
2446 	}
2447 
2448 	mutex_unlock(&bpf_module_mutex);
2449 
2450 out:
2451 	return notifier_from_errno(ret);
2452 }
2453 
2454 static struct notifier_block bpf_module_nb = {
2455 	.notifier_call = bpf_event_notify,
2456 };
2457 
bpf_event_init(void)2458 static int __init bpf_event_init(void)
2459 {
2460 	register_module_notifier(&bpf_module_nb);
2461 	return 0;
2462 }
2463 
2464 fs_initcall(bpf_event_init);
2465 #endif /* CONFIG_MODULES */
2466 
2467 #ifdef CONFIG_FPROBE
2468 struct bpf_kprobe_multi_link {
2469 	struct bpf_link link;
2470 	struct fprobe fp;
2471 	unsigned long *addrs;
2472 	u64 *cookies;
2473 	u32 cnt;
2474 };
2475 
2476 struct bpf_kprobe_multi_run_ctx {
2477 	struct bpf_run_ctx run_ctx;
2478 	struct bpf_kprobe_multi_link *link;
2479 	unsigned long entry_ip;
2480 };
2481 
2482 struct user_syms {
2483 	const char **syms;
2484 	char *buf;
2485 };
2486 
copy_user_syms(struct user_syms * us,unsigned long __user * usyms,u32 cnt)2487 static int copy_user_syms(struct user_syms *us, unsigned long __user *usyms, u32 cnt)
2488 {
2489 	unsigned long __user usymbol;
2490 	const char **syms = NULL;
2491 	char *buf = NULL, *p;
2492 	int err = -ENOMEM;
2493 	unsigned int i;
2494 
2495 	syms = kvmalloc_array(cnt, sizeof(*syms), GFP_KERNEL);
2496 	if (!syms)
2497 		goto error;
2498 
2499 	buf = kvmalloc_array(cnt, KSYM_NAME_LEN, GFP_KERNEL);
2500 	if (!buf)
2501 		goto error;
2502 
2503 	for (p = buf, i = 0; i < cnt; i++) {
2504 		if (__get_user(usymbol, usyms + i)) {
2505 			err = -EFAULT;
2506 			goto error;
2507 		}
2508 		err = strncpy_from_user(p, (const char __user *) usymbol, KSYM_NAME_LEN);
2509 		if (err == KSYM_NAME_LEN)
2510 			err = -E2BIG;
2511 		if (err < 0)
2512 			goto error;
2513 		syms[i] = p;
2514 		p += err + 1;
2515 	}
2516 
2517 	us->syms = syms;
2518 	us->buf = buf;
2519 	return 0;
2520 
2521 error:
2522 	if (err) {
2523 		kvfree(syms);
2524 		kvfree(buf);
2525 	}
2526 	return err;
2527 }
2528 
free_user_syms(struct user_syms * us)2529 static void free_user_syms(struct user_syms *us)
2530 {
2531 	kvfree(us->syms);
2532 	kvfree(us->buf);
2533 }
2534 
bpf_kprobe_multi_link_release(struct bpf_link * link)2535 static void bpf_kprobe_multi_link_release(struct bpf_link *link)
2536 {
2537 	struct bpf_kprobe_multi_link *kmulti_link;
2538 
2539 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2540 	unregister_fprobe(&kmulti_link->fp);
2541 }
2542 
bpf_kprobe_multi_link_dealloc(struct bpf_link * link)2543 static void bpf_kprobe_multi_link_dealloc(struct bpf_link *link)
2544 {
2545 	struct bpf_kprobe_multi_link *kmulti_link;
2546 
2547 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2548 	kvfree(kmulti_link->addrs);
2549 	kvfree(kmulti_link->cookies);
2550 	kfree(kmulti_link);
2551 }
2552 
2553 static const struct bpf_link_ops bpf_kprobe_multi_link_lops = {
2554 	.release = bpf_kprobe_multi_link_release,
2555 	.dealloc = bpf_kprobe_multi_link_dealloc,
2556 };
2557 
bpf_kprobe_multi_cookie_swap(void * a,void * b,int size,const void * priv)2558 static void bpf_kprobe_multi_cookie_swap(void *a, void *b, int size, const void *priv)
2559 {
2560 	const struct bpf_kprobe_multi_link *link = priv;
2561 	unsigned long *addr_a = a, *addr_b = b;
2562 	u64 *cookie_a, *cookie_b;
2563 
2564 	cookie_a = link->cookies + (addr_a - link->addrs);
2565 	cookie_b = link->cookies + (addr_b - link->addrs);
2566 
2567 	/* swap addr_a/addr_b and cookie_a/cookie_b values */
2568 	swap(*addr_a, *addr_b);
2569 	swap(*cookie_a, *cookie_b);
2570 }
2571 
__bpf_kprobe_multi_cookie_cmp(const void * a,const void * b)2572 static int __bpf_kprobe_multi_cookie_cmp(const void *a, const void *b)
2573 {
2574 	const unsigned long *addr_a = a, *addr_b = b;
2575 
2576 	if (*addr_a == *addr_b)
2577 		return 0;
2578 	return *addr_a < *addr_b ? -1 : 1;
2579 }
2580 
bpf_kprobe_multi_cookie_cmp(const void * a,const void * b,const void * priv)2581 static int bpf_kprobe_multi_cookie_cmp(const void *a, const void *b, const void *priv)
2582 {
2583 	return __bpf_kprobe_multi_cookie_cmp(a, b);
2584 }
2585 
bpf_kprobe_multi_cookie(struct bpf_run_ctx * ctx)2586 static u64 bpf_kprobe_multi_cookie(struct bpf_run_ctx *ctx)
2587 {
2588 	struct bpf_kprobe_multi_run_ctx *run_ctx;
2589 	struct bpf_kprobe_multi_link *link;
2590 	u64 *cookie, entry_ip;
2591 	unsigned long *addr;
2592 
2593 	if (WARN_ON_ONCE(!ctx))
2594 		return 0;
2595 	run_ctx = container_of(current->bpf_ctx, struct bpf_kprobe_multi_run_ctx, run_ctx);
2596 	link = run_ctx->link;
2597 	if (!link->cookies)
2598 		return 0;
2599 	entry_ip = run_ctx->entry_ip;
2600 	addr = bsearch(&entry_ip, link->addrs, link->cnt, sizeof(entry_ip),
2601 		       __bpf_kprobe_multi_cookie_cmp);
2602 	if (!addr)
2603 		return 0;
2604 	cookie = link->cookies + (addr - link->addrs);
2605 	return *cookie;
2606 }
2607 
bpf_kprobe_multi_entry_ip(struct bpf_run_ctx * ctx)2608 static u64 bpf_kprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
2609 {
2610 	struct bpf_kprobe_multi_run_ctx *run_ctx;
2611 
2612 	run_ctx = container_of(current->bpf_ctx, struct bpf_kprobe_multi_run_ctx, run_ctx);
2613 	return run_ctx->entry_ip;
2614 }
2615 
2616 static int
kprobe_multi_link_prog_run(struct bpf_kprobe_multi_link * link,unsigned long entry_ip,struct pt_regs * regs)2617 kprobe_multi_link_prog_run(struct bpf_kprobe_multi_link *link,
2618 			   unsigned long entry_ip, struct pt_regs *regs)
2619 {
2620 	struct bpf_kprobe_multi_run_ctx run_ctx = {
2621 		.link = link,
2622 		.entry_ip = entry_ip,
2623 	};
2624 	struct bpf_run_ctx *old_run_ctx;
2625 	int err;
2626 
2627 	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) {
2628 		err = 0;
2629 		goto out;
2630 	}
2631 
2632 	migrate_disable();
2633 	rcu_read_lock();
2634 	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
2635 	err = bpf_prog_run(link->link.prog, regs);
2636 	bpf_reset_run_ctx(old_run_ctx);
2637 	rcu_read_unlock();
2638 	migrate_enable();
2639 
2640  out:
2641 	__this_cpu_dec(bpf_prog_active);
2642 	return err;
2643 }
2644 
2645 static void
kprobe_multi_link_handler(struct fprobe * fp,unsigned long fentry_ip,struct pt_regs * regs,void * data)2646 kprobe_multi_link_handler(struct fprobe *fp, unsigned long fentry_ip,
2647 			  struct pt_regs *regs, void *data)
2648 {
2649 	struct bpf_kprobe_multi_link *link;
2650 
2651 	link = container_of(fp, struct bpf_kprobe_multi_link, fp);
2652 	kprobe_multi_link_prog_run(link, get_entry_ip(fentry_ip), regs);
2653 }
2654 
symbols_cmp_r(const void * a,const void * b,const void * priv)2655 static int symbols_cmp_r(const void *a, const void *b, const void *priv)
2656 {
2657 	const char **str_a = (const char **) a;
2658 	const char **str_b = (const char **) b;
2659 
2660 	return strcmp(*str_a, *str_b);
2661 }
2662 
2663 struct multi_symbols_sort {
2664 	const char **funcs;
2665 	u64 *cookies;
2666 };
2667 
symbols_swap_r(void * a,void * b,int size,const void * priv)2668 static void symbols_swap_r(void *a, void *b, int size, const void *priv)
2669 {
2670 	const struct multi_symbols_sort *data = priv;
2671 	const char **name_a = a, **name_b = b;
2672 
2673 	swap(*name_a, *name_b);
2674 
2675 	/* If defined, swap also related cookies. */
2676 	if (data->cookies) {
2677 		u64 *cookie_a, *cookie_b;
2678 
2679 		cookie_a = data->cookies + (name_a - data->funcs);
2680 		cookie_b = data->cookies + (name_b - data->funcs);
2681 		swap(*cookie_a, *cookie_b);
2682 	}
2683 }
2684 
addrs_check_error_injection_list(unsigned long * addrs,u32 cnt)2685 static int addrs_check_error_injection_list(unsigned long *addrs, u32 cnt)
2686 {
2687 	u32 i;
2688 
2689 	for (i = 0; i < cnt; i++) {
2690 		if (!within_error_injection_list(addrs[i]))
2691 			return -EINVAL;
2692 	}
2693 	return 0;
2694 }
2695 
bpf_kprobe_multi_link_attach(const union bpf_attr * attr,struct bpf_prog * prog)2696 int bpf_kprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
2697 {
2698 	struct bpf_kprobe_multi_link *link = NULL;
2699 	struct bpf_link_primer link_primer;
2700 	void __user *ucookies;
2701 	unsigned long *addrs;
2702 	u32 flags, cnt, size;
2703 	void __user *uaddrs;
2704 	u64 *cookies = NULL;
2705 	void __user *usyms;
2706 	int err;
2707 
2708 	/* no support for 32bit archs yet */
2709 	if (sizeof(u64) != sizeof(void *))
2710 		return -EOPNOTSUPP;
2711 
2712 	if (prog->expected_attach_type != BPF_TRACE_KPROBE_MULTI)
2713 		return -EINVAL;
2714 
2715 	flags = attr->link_create.kprobe_multi.flags;
2716 	if (flags & ~BPF_F_KPROBE_MULTI_RETURN)
2717 		return -EINVAL;
2718 
2719 	uaddrs = u64_to_user_ptr(attr->link_create.kprobe_multi.addrs);
2720 	usyms = u64_to_user_ptr(attr->link_create.kprobe_multi.syms);
2721 	if (!!uaddrs == !!usyms)
2722 		return -EINVAL;
2723 
2724 	cnt = attr->link_create.kprobe_multi.cnt;
2725 	if (!cnt)
2726 		return -EINVAL;
2727 
2728 	size = cnt * sizeof(*addrs);
2729 	addrs = kvmalloc_array(cnt, sizeof(*addrs), GFP_KERNEL);
2730 	if (!addrs)
2731 		return -ENOMEM;
2732 
2733 	ucookies = u64_to_user_ptr(attr->link_create.kprobe_multi.cookies);
2734 	if (ucookies) {
2735 		cookies = kvmalloc_array(cnt, sizeof(*addrs), GFP_KERNEL);
2736 		if (!cookies) {
2737 			err = -ENOMEM;
2738 			goto error;
2739 		}
2740 		if (copy_from_user(cookies, ucookies, size)) {
2741 			err = -EFAULT;
2742 			goto error;
2743 		}
2744 	}
2745 
2746 	if (uaddrs) {
2747 		if (copy_from_user(addrs, uaddrs, size)) {
2748 			err = -EFAULT;
2749 			goto error;
2750 		}
2751 	} else {
2752 		struct multi_symbols_sort data = {
2753 			.cookies = cookies,
2754 		};
2755 		struct user_syms us;
2756 
2757 		err = copy_user_syms(&us, usyms, cnt);
2758 		if (err)
2759 			goto error;
2760 
2761 		if (cookies)
2762 			data.funcs = us.syms;
2763 
2764 		sort_r(us.syms, cnt, sizeof(*us.syms), symbols_cmp_r,
2765 		       symbols_swap_r, &data);
2766 
2767 		err = ftrace_lookup_symbols(us.syms, cnt, addrs);
2768 		free_user_syms(&us);
2769 		if (err)
2770 			goto error;
2771 	}
2772 
2773 	if (prog->kprobe_override && addrs_check_error_injection_list(addrs, cnt)) {
2774 		err = -EINVAL;
2775 		goto error;
2776 	}
2777 
2778 	link = kzalloc(sizeof(*link), GFP_KERNEL);
2779 	if (!link) {
2780 		err = -ENOMEM;
2781 		goto error;
2782 	}
2783 
2784 	bpf_link_init(&link->link, BPF_LINK_TYPE_KPROBE_MULTI,
2785 		      &bpf_kprobe_multi_link_lops, prog);
2786 
2787 	err = bpf_link_prime(&link->link, &link_primer);
2788 	if (err)
2789 		goto error;
2790 
2791 	if (flags & BPF_F_KPROBE_MULTI_RETURN)
2792 		link->fp.exit_handler = kprobe_multi_link_handler;
2793 	else
2794 		link->fp.entry_handler = kprobe_multi_link_handler;
2795 
2796 	link->addrs = addrs;
2797 	link->cookies = cookies;
2798 	link->cnt = cnt;
2799 
2800 	if (cookies) {
2801 		/*
2802 		 * Sorting addresses will trigger sorting cookies as well
2803 		 * (check bpf_kprobe_multi_cookie_swap). This way we can
2804 		 * find cookie based on the address in bpf_get_attach_cookie
2805 		 * helper.
2806 		 */
2807 		sort_r(addrs, cnt, sizeof(*addrs),
2808 		       bpf_kprobe_multi_cookie_cmp,
2809 		       bpf_kprobe_multi_cookie_swap,
2810 		       link);
2811 	}
2812 
2813 	err = register_fprobe_ips(&link->fp, addrs, cnt);
2814 	if (err) {
2815 		bpf_link_cleanup(&link_primer);
2816 		return err;
2817 	}
2818 
2819 	return bpf_link_settle(&link_primer);
2820 
2821 error:
2822 	kfree(link);
2823 	kvfree(addrs);
2824 	kvfree(cookies);
2825 	return err;
2826 }
2827 #else /* !CONFIG_FPROBE */
bpf_kprobe_multi_link_attach(const union bpf_attr * attr,struct bpf_prog * prog)2828 int bpf_kprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
2829 {
2830 	return -EOPNOTSUPP;
2831 }
bpf_kprobe_multi_cookie(struct bpf_run_ctx * ctx)2832 static u64 bpf_kprobe_multi_cookie(struct bpf_run_ctx *ctx)
2833 {
2834 	return 0;
2835 }
bpf_kprobe_multi_entry_ip(struct bpf_run_ctx * ctx)2836 static u64 bpf_kprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
2837 {
2838 	return 0;
2839 }
2840 #endif
2841