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