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