60e82c7b812261a6897ba69b6c3ab7eb623f4c44
[platform/kernel/linux-starfive.git] / kernel / trace / bpf_trace.c
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2011-2015 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  */
5 #include <linux/kernel.h>
6 #include <linux/types.h>
7 #include <linux/slab.h>
8 #include <linux/bpf.h>
9 #include <linux/bpf_perf_event.h>
10 #include <linux/filter.h>
11 #include <linux/uaccess.h>
12 #include <linux/ctype.h>
13 #include <linux/kprobes.h>
14 #include <linux/syscalls.h>
15 #include <linux/error-injection.h>
16
17 #include <asm/tlb.h>
18
19 #include "trace_probe.h"
20 #include "trace.h"
21
22 #define bpf_event_rcu_dereference(p)                                    \
23         rcu_dereference_protected(p, lockdep_is_held(&bpf_event_mutex))
24
25 #ifdef CONFIG_MODULES
26 struct bpf_trace_module {
27         struct module *module;
28         struct list_head list;
29 };
30
31 static LIST_HEAD(bpf_trace_modules);
32 static DEFINE_MUTEX(bpf_module_mutex);
33
34 static struct bpf_raw_event_map *bpf_get_raw_tracepoint_module(const char *name)
35 {
36         struct bpf_raw_event_map *btp, *ret = NULL;
37         struct bpf_trace_module *btm;
38         unsigned int i;
39
40         mutex_lock(&bpf_module_mutex);
41         list_for_each_entry(btm, &bpf_trace_modules, list) {
42                 for (i = 0; i < btm->module->num_bpf_raw_events; ++i) {
43                         btp = &btm->module->bpf_raw_events[i];
44                         if (!strcmp(btp->tp->name, name)) {
45                                 if (try_module_get(btm->module))
46                                         ret = btp;
47                                 goto out;
48                         }
49                 }
50         }
51 out:
52         mutex_unlock(&bpf_module_mutex);
53         return ret;
54 }
55 #else
56 static struct bpf_raw_event_map *bpf_get_raw_tracepoint_module(const char *name)
57 {
58         return NULL;
59 }
60 #endif /* CONFIG_MODULES */
61
62 u64 bpf_get_stackid(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
63 u64 bpf_get_stack(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
64
65 /**
66  * trace_call_bpf - invoke BPF program
67  * @call: tracepoint event
68  * @ctx: opaque context pointer
69  *
70  * kprobe handlers execute BPF programs via this helper.
71  * Can be used from static tracepoints in the future.
72  *
73  * Return: BPF programs always return an integer which is interpreted by
74  * kprobe handler as:
75  * 0 - return from kprobe (event is filtered out)
76  * 1 - store kprobe event into ring buffer
77  * Other values are reserved and currently alias to 1
78  */
79 unsigned int trace_call_bpf(struct trace_event_call *call, void *ctx)
80 {
81         unsigned int ret;
82
83         if (in_nmi()) /* not supported yet */
84                 return 1;
85
86         cant_sleep();
87
88         if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) {
89                 /*
90                  * since some bpf program is already running on this cpu,
91                  * don't call into another bpf program (same or different)
92                  * and don't send kprobe event into ring-buffer,
93                  * so return zero here
94                  */
95                 ret = 0;
96                 goto out;
97         }
98
99         /*
100          * Instead of moving rcu_read_lock/rcu_dereference/rcu_read_unlock
101          * to all call sites, we did a bpf_prog_array_valid() there to check
102          * whether call->prog_array is empty or not, which is
103          * a heurisitc to speed up execution.
104          *
105          * If bpf_prog_array_valid() fetched prog_array was
106          * non-NULL, we go into trace_call_bpf() and do the actual
107          * proper rcu_dereference() under RCU lock.
108          * If it turns out that prog_array is NULL then, we bail out.
109          * For the opposite, if the bpf_prog_array_valid() fetched pointer
110          * was NULL, you'll skip the prog_array with the risk of missing
111          * out of events when it was updated in between this and the
112          * rcu_dereference() which is accepted risk.
113          */
114         ret = BPF_PROG_RUN_ARRAY_CHECK(call->prog_array, ctx, BPF_PROG_RUN);
115
116  out:
117         __this_cpu_dec(bpf_prog_active);
118
119         return ret;
120 }
121
122 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
123 BPF_CALL_2(bpf_override_return, struct pt_regs *, regs, unsigned long, rc)
124 {
125         regs_set_return_value(regs, rc);
126         override_function_with_return(regs);
127         return 0;
128 }
129
130 static const struct bpf_func_proto bpf_override_return_proto = {
131         .func           = bpf_override_return,
132         .gpl_only       = true,
133         .ret_type       = RET_INTEGER,
134         .arg1_type      = ARG_PTR_TO_CTX,
135         .arg2_type      = ARG_ANYTHING,
136 };
137 #endif
138
139 BPF_CALL_3(bpf_probe_read_user, void *, dst, u32, size,
140            const void __user *, unsafe_ptr)
141 {
142         int ret = probe_user_read(dst, unsafe_ptr, size);
143
144         if (unlikely(ret < 0))
145                 memset(dst, 0, size);
146
147         return ret;
148 }
149
150 const struct bpf_func_proto bpf_probe_read_user_proto = {
151         .func           = bpf_probe_read_user,
152         .gpl_only       = true,
153         .ret_type       = RET_INTEGER,
154         .arg1_type      = ARG_PTR_TO_UNINIT_MEM,
155         .arg2_type      = ARG_CONST_SIZE_OR_ZERO,
156         .arg3_type      = ARG_ANYTHING,
157 };
158
159 BPF_CALL_3(bpf_probe_read_user_str, void *, dst, u32, size,
160            const void __user *, unsafe_ptr)
161 {
162         int ret = strncpy_from_user_nofault(dst, unsafe_ptr, size);
163
164         if (unlikely(ret < 0))
165                 memset(dst, 0, size);
166
167         return ret;
168 }
169
170 const struct bpf_func_proto bpf_probe_read_user_str_proto = {
171         .func           = bpf_probe_read_user_str,
172         .gpl_only       = true,
173         .ret_type       = RET_INTEGER,
174         .arg1_type      = ARG_PTR_TO_UNINIT_MEM,
175         .arg2_type      = ARG_CONST_SIZE_OR_ZERO,
176         .arg3_type      = ARG_ANYTHING,
177 };
178
179 static __always_inline int
180 bpf_probe_read_kernel_common(void *dst, u32 size, const void *unsafe_ptr,
181                              const bool compat)
182 {
183         int ret = security_locked_down(LOCKDOWN_BPF_READ);
184
185         if (unlikely(ret < 0))
186                 goto out;
187         ret = compat ? probe_kernel_read(dst, unsafe_ptr, size) :
188               probe_kernel_read_strict(dst, unsafe_ptr, size);
189         if (unlikely(ret < 0))
190 out:
191                 memset(dst, 0, size);
192         return ret;
193 }
194
195 BPF_CALL_3(bpf_probe_read_kernel, void *, dst, u32, size,
196            const void *, unsafe_ptr)
197 {
198         return bpf_probe_read_kernel_common(dst, size, unsafe_ptr, false);
199 }
200
201 const struct bpf_func_proto bpf_probe_read_kernel_proto = {
202         .func           = bpf_probe_read_kernel,
203         .gpl_only       = true,
204         .ret_type       = RET_INTEGER,
205         .arg1_type      = ARG_PTR_TO_UNINIT_MEM,
206         .arg2_type      = ARG_CONST_SIZE_OR_ZERO,
207         .arg3_type      = ARG_ANYTHING,
208 };
209
210 BPF_CALL_3(bpf_probe_read_compat, void *, dst, u32, size,
211            const void *, unsafe_ptr)
212 {
213         return bpf_probe_read_kernel_common(dst, size, unsafe_ptr, true);
214 }
215
216 static const struct bpf_func_proto bpf_probe_read_compat_proto = {
217         .func           = bpf_probe_read_compat,
218         .gpl_only       = true,
219         .ret_type       = RET_INTEGER,
220         .arg1_type      = ARG_PTR_TO_UNINIT_MEM,
221         .arg2_type      = ARG_CONST_SIZE_OR_ZERO,
222         .arg3_type      = ARG_ANYTHING,
223 };
224
225 static __always_inline int
226 bpf_probe_read_kernel_str_common(void *dst, u32 size, const void *unsafe_ptr,
227                                  const bool compat)
228 {
229         int ret = security_locked_down(LOCKDOWN_BPF_READ);
230
231         if (unlikely(ret < 0))
232                 goto out;
233         /*
234          * The strncpy_from_unsafe_*() call will likely not fill the entire
235          * buffer, but that's okay in this circumstance as we're probing
236          * arbitrary memory anyway similar to bpf_probe_read_*() and might
237          * as well probe the stack. Thus, memory is explicitly cleared
238          * only in error case, so that improper users ignoring return
239          * code altogether don't copy garbage; otherwise length of string
240          * is returned that can be used for bpf_perf_event_output() et al.
241          */
242         ret = compat ? strncpy_from_unsafe(dst, unsafe_ptr, size) :
243               strncpy_from_kernel_nofault(dst, unsafe_ptr, size);
244         if (unlikely(ret < 0))
245 out:
246                 memset(dst, 0, size);
247         return ret;
248 }
249
250 BPF_CALL_3(bpf_probe_read_kernel_str, void *, dst, u32, size,
251            const void *, unsafe_ptr)
252 {
253         return bpf_probe_read_kernel_str_common(dst, size, unsafe_ptr, false);
254 }
255
256 const struct bpf_func_proto bpf_probe_read_kernel_str_proto = {
257         .func           = bpf_probe_read_kernel_str,
258         .gpl_only       = true,
259         .ret_type       = RET_INTEGER,
260         .arg1_type      = ARG_PTR_TO_UNINIT_MEM,
261         .arg2_type      = ARG_CONST_SIZE_OR_ZERO,
262         .arg3_type      = ARG_ANYTHING,
263 };
264
265 BPF_CALL_3(bpf_probe_read_compat_str, void *, dst, u32, size,
266            const void *, unsafe_ptr)
267 {
268         return bpf_probe_read_kernel_str_common(dst, size, unsafe_ptr, true);
269 }
270
271 static const struct bpf_func_proto bpf_probe_read_compat_str_proto = {
272         .func           = bpf_probe_read_compat_str,
273         .gpl_only       = true,
274         .ret_type       = RET_INTEGER,
275         .arg1_type      = ARG_PTR_TO_UNINIT_MEM,
276         .arg2_type      = ARG_CONST_SIZE_OR_ZERO,
277         .arg3_type      = ARG_ANYTHING,
278 };
279
280 BPF_CALL_3(bpf_probe_write_user, void __user *, unsafe_ptr, const void *, src,
281            u32, size)
282 {
283         /*
284          * Ensure we're in user context which is safe for the helper to
285          * run. This helper has no business in a kthread.
286          *
287          * access_ok() should prevent writing to non-user memory, but in
288          * some situations (nommu, temporary switch, etc) access_ok() does
289          * not provide enough validation, hence the check on KERNEL_DS.
290          *
291          * nmi_uaccess_okay() ensures the probe is not run in an interim
292          * state, when the task or mm are switched. This is specifically
293          * required to prevent the use of temporary mm.
294          */
295
296         if (unlikely(in_interrupt() ||
297                      current->flags & (PF_KTHREAD | PF_EXITING)))
298                 return -EPERM;
299         if (unlikely(uaccess_kernel()))
300                 return -EPERM;
301         if (unlikely(!nmi_uaccess_okay()))
302                 return -EPERM;
303
304         return probe_user_write(unsafe_ptr, src, size);
305 }
306
307 static const struct bpf_func_proto bpf_probe_write_user_proto = {
308         .func           = bpf_probe_write_user,
309         .gpl_only       = true,
310         .ret_type       = RET_INTEGER,
311         .arg1_type      = ARG_ANYTHING,
312         .arg2_type      = ARG_PTR_TO_MEM,
313         .arg3_type      = ARG_CONST_SIZE,
314 };
315
316 static const struct bpf_func_proto *bpf_get_probe_write_proto(void)
317 {
318         if (!capable(CAP_SYS_ADMIN))
319                 return NULL;
320
321         pr_warn_ratelimited("%s[%d] is installing a program with bpf_probe_write_user helper that may corrupt user memory!",
322                             current->comm, task_pid_nr(current));
323
324         return &bpf_probe_write_user_proto;
325 }
326
327 static void bpf_trace_copy_string(char *buf, void *unsafe_ptr, char fmt_ptype,
328                 size_t bufsz)
329 {
330         void __user *user_ptr = (__force void __user *)unsafe_ptr;
331
332         buf[0] = 0;
333
334         switch (fmt_ptype) {
335         case 's':
336 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
337                 strncpy_from_unsafe(buf, unsafe_ptr, bufsz);
338                 break;
339 #endif
340         case 'k':
341                 strncpy_from_kernel_nofault(buf, unsafe_ptr, bufsz);
342                 break;
343         case 'u':
344                 strncpy_from_user_nofault(buf, user_ptr, bufsz);
345                 break;
346         }
347 }
348
349 /*
350  * Only limited trace_printk() conversion specifiers allowed:
351  * %d %i %u %x %ld %li %lu %lx %lld %lli %llu %llx %p %pks %pus %s
352  */
353 BPF_CALL_5(bpf_trace_printk, char *, fmt, u32, fmt_size, u64, arg1,
354            u64, arg2, u64, arg3)
355 {
356         int i, mod[3] = {}, fmt_cnt = 0;
357         char buf[64], fmt_ptype;
358         void *unsafe_ptr = NULL;
359         bool str_seen = false;
360
361         /*
362          * bpf_check()->check_func_arg()->check_stack_boundary()
363          * guarantees that fmt points to bpf program stack,
364          * fmt_size bytes of it were initialized and fmt_size > 0
365          */
366         if (fmt[--fmt_size] != 0)
367                 return -EINVAL;
368
369         /* check format string for allowed specifiers */
370         for (i = 0; i < fmt_size; i++) {
371                 if ((!isprint(fmt[i]) && !isspace(fmt[i])) || !isascii(fmt[i]))
372                         return -EINVAL;
373
374                 if (fmt[i] != '%')
375                         continue;
376
377                 if (fmt_cnt >= 3)
378                         return -EINVAL;
379
380                 /* fmt[i] != 0 && fmt[last] == 0, so we can access fmt[i + 1] */
381                 i++;
382                 if (fmt[i] == 'l') {
383                         mod[fmt_cnt]++;
384                         i++;
385                 } else if (fmt[i] == 'p') {
386                         mod[fmt_cnt]++;
387                         if ((fmt[i + 1] == 'k' ||
388                              fmt[i + 1] == 'u') &&
389                             fmt[i + 2] == 's') {
390                                 fmt_ptype = fmt[i + 1];
391                                 i += 2;
392                                 goto fmt_str;
393                         }
394
395                         /* disallow any further format extensions */
396                         if (fmt[i + 1] != 0 &&
397                             !isspace(fmt[i + 1]) &&
398                             !ispunct(fmt[i + 1]))
399                                 return -EINVAL;
400
401                         goto fmt_next;
402                 } else if (fmt[i] == 's') {
403                         mod[fmt_cnt]++;
404                         fmt_ptype = fmt[i];
405 fmt_str:
406                         if (str_seen)
407                                 /* allow only one '%s' per fmt string */
408                                 return -EINVAL;
409                         str_seen = true;
410
411                         if (fmt[i + 1] != 0 &&
412                             !isspace(fmt[i + 1]) &&
413                             !ispunct(fmt[i + 1]))
414                                 return -EINVAL;
415
416                         switch (fmt_cnt) {
417                         case 0:
418                                 unsafe_ptr = (void *)(long)arg1;
419                                 arg1 = (long)buf;
420                                 break;
421                         case 1:
422                                 unsafe_ptr = (void *)(long)arg2;
423                                 arg2 = (long)buf;
424                                 break;
425                         case 2:
426                                 unsafe_ptr = (void *)(long)arg3;
427                                 arg3 = (long)buf;
428                                 break;
429                         }
430
431                         bpf_trace_copy_string(buf, unsafe_ptr, fmt_ptype,
432                                         sizeof(buf));
433                         goto fmt_next;
434                 }
435
436                 if (fmt[i] == 'l') {
437                         mod[fmt_cnt]++;
438                         i++;
439                 }
440
441                 if (fmt[i] != 'i' && fmt[i] != 'd' &&
442                     fmt[i] != 'u' && fmt[i] != 'x')
443                         return -EINVAL;
444 fmt_next:
445                 fmt_cnt++;
446         }
447
448 /* Horrid workaround for getting va_list handling working with different
449  * argument type combinations generically for 32 and 64 bit archs.
450  */
451 #define __BPF_TP_EMIT() __BPF_ARG3_TP()
452 #define __BPF_TP(...)                                                   \
453         __trace_printk(0 /* Fake ip */,                                 \
454                        fmt, ##__VA_ARGS__)
455
456 #define __BPF_ARG1_TP(...)                                              \
457         ((mod[0] == 2 || (mod[0] == 1 && __BITS_PER_LONG == 64))        \
458           ? __BPF_TP(arg1, ##__VA_ARGS__)                               \
459           : ((mod[0] == 1 || (mod[0] == 0 && __BITS_PER_LONG == 32))    \
460               ? __BPF_TP((long)arg1, ##__VA_ARGS__)                     \
461               : __BPF_TP((u32)arg1, ##__VA_ARGS__)))
462
463 #define __BPF_ARG2_TP(...)                                              \
464         ((mod[1] == 2 || (mod[1] == 1 && __BITS_PER_LONG == 64))        \
465           ? __BPF_ARG1_TP(arg2, ##__VA_ARGS__)                          \
466           : ((mod[1] == 1 || (mod[1] == 0 && __BITS_PER_LONG == 32))    \
467               ? __BPF_ARG1_TP((long)arg2, ##__VA_ARGS__)                \
468               : __BPF_ARG1_TP((u32)arg2, ##__VA_ARGS__)))
469
470 #define __BPF_ARG3_TP(...)                                              \
471         ((mod[2] == 2 || (mod[2] == 1 && __BITS_PER_LONG == 64))        \
472           ? __BPF_ARG2_TP(arg3, ##__VA_ARGS__)                          \
473           : ((mod[2] == 1 || (mod[2] == 0 && __BITS_PER_LONG == 32))    \
474               ? __BPF_ARG2_TP((long)arg3, ##__VA_ARGS__)                \
475               : __BPF_ARG2_TP((u32)arg3, ##__VA_ARGS__)))
476
477         return __BPF_TP_EMIT();
478 }
479
480 static const struct bpf_func_proto bpf_trace_printk_proto = {
481         .func           = bpf_trace_printk,
482         .gpl_only       = true,
483         .ret_type       = RET_INTEGER,
484         .arg1_type      = ARG_PTR_TO_MEM,
485         .arg2_type      = ARG_CONST_SIZE,
486 };
487
488 const struct bpf_func_proto *bpf_get_trace_printk_proto(void)
489 {
490         /*
491          * this program might be calling bpf_trace_printk,
492          * so allocate per-cpu printk buffers
493          */
494         trace_printk_init_buffers();
495
496         return &bpf_trace_printk_proto;
497 }
498
499 #define MAX_SEQ_PRINTF_VARARGS          12
500 #define MAX_SEQ_PRINTF_MAX_MEMCPY       6
501 #define MAX_SEQ_PRINTF_STR_LEN          128
502
503 struct bpf_seq_printf_buf {
504         char buf[MAX_SEQ_PRINTF_MAX_MEMCPY][MAX_SEQ_PRINTF_STR_LEN];
505 };
506 static DEFINE_PER_CPU(struct bpf_seq_printf_buf, bpf_seq_printf_buf);
507 static DEFINE_PER_CPU(int, bpf_seq_printf_buf_used);
508
509 BPF_CALL_5(bpf_seq_printf, struct seq_file *, m, char *, fmt, u32, fmt_size,
510            const void *, data, u32, data_len)
511 {
512         int err = -EINVAL, fmt_cnt = 0, memcpy_cnt = 0;
513         int i, buf_used, copy_size, num_args;
514         u64 params[MAX_SEQ_PRINTF_VARARGS];
515         struct bpf_seq_printf_buf *bufs;
516         const u64 *args = data;
517
518         buf_used = this_cpu_inc_return(bpf_seq_printf_buf_used);
519         if (WARN_ON_ONCE(buf_used > 1)) {
520                 err = -EBUSY;
521                 goto out;
522         }
523
524         bufs = this_cpu_ptr(&bpf_seq_printf_buf);
525
526         /*
527          * bpf_check()->check_func_arg()->check_stack_boundary()
528          * guarantees that fmt points to bpf program stack,
529          * fmt_size bytes of it were initialized and fmt_size > 0
530          */
531         if (fmt[--fmt_size] != 0)
532                 goto out;
533
534         if (data_len & 7)
535                 goto out;
536
537         for (i = 0; i < fmt_size; i++) {
538                 if (fmt[i] == '%') {
539                         if (fmt[i + 1] == '%')
540                                 i++;
541                         else if (!data || !data_len)
542                                 goto out;
543                 }
544         }
545
546         num_args = data_len / 8;
547
548         /* check format string for allowed specifiers */
549         for (i = 0; i < fmt_size; i++) {
550                 /* only printable ascii for now. */
551                 if ((!isprint(fmt[i]) && !isspace(fmt[i])) || !isascii(fmt[i])) {
552                         err = -EINVAL;
553                         goto out;
554                 }
555
556                 if (fmt[i] != '%')
557                         continue;
558
559                 if (fmt[i + 1] == '%') {
560                         i++;
561                         continue;
562                 }
563
564                 if (fmt_cnt >= MAX_SEQ_PRINTF_VARARGS) {
565                         err = -E2BIG;
566                         goto out;
567                 }
568
569                 if (fmt_cnt >= num_args) {
570                         err = -EINVAL;
571                         goto out;
572                 }
573
574                 /* fmt[i] != 0 && fmt[last] == 0, so we can access fmt[i + 1] */
575                 i++;
576
577                 /* skip optional "[0 +-][num]" width formating field */
578                 while (fmt[i] == '0' || fmt[i] == '+'  || fmt[i] == '-' ||
579                        fmt[i] == ' ')
580                         i++;
581                 if (fmt[i] >= '1' && fmt[i] <= '9') {
582                         i++;
583                         while (fmt[i] >= '0' && fmt[i] <= '9')
584                                 i++;
585                 }
586
587                 if (fmt[i] == 's') {
588                         /* try our best to copy */
589                         if (memcpy_cnt >= MAX_SEQ_PRINTF_MAX_MEMCPY) {
590                                 err = -E2BIG;
591                                 goto out;
592                         }
593
594                         err = strncpy_from_unsafe_strict(bufs->buf[memcpy_cnt],
595                                                          (void *) (long) args[fmt_cnt],
596                                                          MAX_SEQ_PRINTF_STR_LEN);
597                         if (err < 0)
598                                 bufs->buf[memcpy_cnt][0] = '\0';
599                         params[fmt_cnt] = (u64)(long)bufs->buf[memcpy_cnt];
600
601                         fmt_cnt++;
602                         memcpy_cnt++;
603                         continue;
604                 }
605
606                 if (fmt[i] == 'p') {
607                         if (fmt[i + 1] == 0 ||
608                             fmt[i + 1] == 'K' ||
609                             fmt[i + 1] == 'x') {
610                                 /* just kernel pointers */
611                                 params[fmt_cnt] = args[fmt_cnt];
612                                 fmt_cnt++;
613                                 continue;
614                         }
615
616                         /* only support "%pI4", "%pi4", "%pI6" and "%pi6". */
617                         if (fmt[i + 1] != 'i' && fmt[i + 1] != 'I') {
618                                 err = -EINVAL;
619                                 goto out;
620                         }
621                         if (fmt[i + 2] != '4' && fmt[i + 2] != '6') {
622                                 err = -EINVAL;
623                                 goto out;
624                         }
625
626                         if (memcpy_cnt >= MAX_SEQ_PRINTF_MAX_MEMCPY) {
627                                 err = -E2BIG;
628                                 goto out;
629                         }
630
631
632                         copy_size = (fmt[i + 2] == '4') ? 4 : 16;
633
634                         err = probe_kernel_read(bufs->buf[memcpy_cnt],
635                                                 (void *) (long) args[fmt_cnt],
636                                                 copy_size);
637                         if (err < 0)
638                                 memset(bufs->buf[memcpy_cnt], 0, copy_size);
639                         params[fmt_cnt] = (u64)(long)bufs->buf[memcpy_cnt];
640
641                         i += 2;
642                         fmt_cnt++;
643                         memcpy_cnt++;
644                         continue;
645                 }
646
647                 if (fmt[i] == 'l') {
648                         i++;
649                         if (fmt[i] == 'l')
650                                 i++;
651                 }
652
653                 if (fmt[i] != 'i' && fmt[i] != 'd' &&
654                     fmt[i] != 'u' && fmt[i] != 'x') {
655                         err = -EINVAL;
656                         goto out;
657                 }
658
659                 params[fmt_cnt] = args[fmt_cnt];
660                 fmt_cnt++;
661         }
662
663         /* Maximumly we can have MAX_SEQ_PRINTF_VARARGS parameter, just give
664          * all of them to seq_printf().
665          */
666         seq_printf(m, fmt, params[0], params[1], params[2], params[3],
667                    params[4], params[5], params[6], params[7], params[8],
668                    params[9], params[10], params[11]);
669
670         err = seq_has_overflowed(m) ? -EOVERFLOW : 0;
671 out:
672         this_cpu_dec(bpf_seq_printf_buf_used);
673         return err;
674 }
675
676 static int bpf_seq_printf_btf_ids[5];
677 static const struct bpf_func_proto bpf_seq_printf_proto = {
678         .func           = bpf_seq_printf,
679         .gpl_only       = true,
680         .ret_type       = RET_INTEGER,
681         .arg1_type      = ARG_PTR_TO_BTF_ID,
682         .arg2_type      = ARG_PTR_TO_MEM,
683         .arg3_type      = ARG_CONST_SIZE,
684         .arg4_type      = ARG_PTR_TO_MEM_OR_NULL,
685         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
686         .btf_id         = bpf_seq_printf_btf_ids,
687 };
688
689 BPF_CALL_3(bpf_seq_write, struct seq_file *, m, const void *, data, u32, len)
690 {
691         return seq_write(m, data, len) ? -EOVERFLOW : 0;
692 }
693
694 static int bpf_seq_write_btf_ids[5];
695 static const struct bpf_func_proto bpf_seq_write_proto = {
696         .func           = bpf_seq_write,
697         .gpl_only       = true,
698         .ret_type       = RET_INTEGER,
699         .arg1_type      = ARG_PTR_TO_BTF_ID,
700         .arg2_type      = ARG_PTR_TO_MEM,
701         .arg3_type      = ARG_CONST_SIZE_OR_ZERO,
702         .btf_id         = bpf_seq_write_btf_ids,
703 };
704
705 static __always_inline int
706 get_map_perf_counter(struct bpf_map *map, u64 flags,
707                      u64 *value, u64 *enabled, u64 *running)
708 {
709         struct bpf_array *array = container_of(map, struct bpf_array, map);
710         unsigned int cpu = smp_processor_id();
711         u64 index = flags & BPF_F_INDEX_MASK;
712         struct bpf_event_entry *ee;
713
714         if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
715                 return -EINVAL;
716         if (index == BPF_F_CURRENT_CPU)
717                 index = cpu;
718         if (unlikely(index >= array->map.max_entries))
719                 return -E2BIG;
720
721         ee = READ_ONCE(array->ptrs[index]);
722         if (!ee)
723                 return -ENOENT;
724
725         return perf_event_read_local(ee->event, value, enabled, running);
726 }
727
728 BPF_CALL_2(bpf_perf_event_read, struct bpf_map *, map, u64, flags)
729 {
730         u64 value = 0;
731         int err;
732
733         err = get_map_perf_counter(map, flags, &value, NULL, NULL);
734         /*
735          * this api is ugly since we miss [-22..-2] range of valid
736          * counter values, but that's uapi
737          */
738         if (err)
739                 return err;
740         return value;
741 }
742
743 static const struct bpf_func_proto bpf_perf_event_read_proto = {
744         .func           = bpf_perf_event_read,
745         .gpl_only       = true,
746         .ret_type       = RET_INTEGER,
747         .arg1_type      = ARG_CONST_MAP_PTR,
748         .arg2_type      = ARG_ANYTHING,
749 };
750
751 BPF_CALL_4(bpf_perf_event_read_value, struct bpf_map *, map, u64, flags,
752            struct bpf_perf_event_value *, buf, u32, size)
753 {
754         int err = -EINVAL;
755
756         if (unlikely(size != sizeof(struct bpf_perf_event_value)))
757                 goto clear;
758         err = get_map_perf_counter(map, flags, &buf->counter, &buf->enabled,
759                                    &buf->running);
760         if (unlikely(err))
761                 goto clear;
762         return 0;
763 clear:
764         memset(buf, 0, size);
765         return err;
766 }
767
768 static const struct bpf_func_proto bpf_perf_event_read_value_proto = {
769         .func           = bpf_perf_event_read_value,
770         .gpl_only       = true,
771         .ret_type       = RET_INTEGER,
772         .arg1_type      = ARG_CONST_MAP_PTR,
773         .arg2_type      = ARG_ANYTHING,
774         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
775         .arg4_type      = ARG_CONST_SIZE,
776 };
777
778 static __always_inline u64
779 __bpf_perf_event_output(struct pt_regs *regs, struct bpf_map *map,
780                         u64 flags, struct perf_sample_data *sd)
781 {
782         struct bpf_array *array = container_of(map, struct bpf_array, map);
783         unsigned int cpu = smp_processor_id();
784         u64 index = flags & BPF_F_INDEX_MASK;
785         struct bpf_event_entry *ee;
786         struct perf_event *event;
787
788         if (index == BPF_F_CURRENT_CPU)
789                 index = cpu;
790         if (unlikely(index >= array->map.max_entries))
791                 return -E2BIG;
792
793         ee = READ_ONCE(array->ptrs[index]);
794         if (!ee)
795                 return -ENOENT;
796
797         event = ee->event;
798         if (unlikely(event->attr.type != PERF_TYPE_SOFTWARE ||
799                      event->attr.config != PERF_COUNT_SW_BPF_OUTPUT))
800                 return -EINVAL;
801
802         if (unlikely(event->oncpu != cpu))
803                 return -EOPNOTSUPP;
804
805         return perf_event_output(event, sd, regs);
806 }
807
808 /*
809  * Support executing tracepoints in normal, irq, and nmi context that each call
810  * bpf_perf_event_output
811  */
812 struct bpf_trace_sample_data {
813         struct perf_sample_data sds[3];
814 };
815
816 static DEFINE_PER_CPU(struct bpf_trace_sample_data, bpf_trace_sds);
817 static DEFINE_PER_CPU(int, bpf_trace_nest_level);
818 BPF_CALL_5(bpf_perf_event_output, struct pt_regs *, regs, struct bpf_map *, map,
819            u64, flags, void *, data, u64, size)
820 {
821         struct bpf_trace_sample_data *sds = this_cpu_ptr(&bpf_trace_sds);
822         int nest_level = this_cpu_inc_return(bpf_trace_nest_level);
823         struct perf_raw_record raw = {
824                 .frag = {
825                         .size = size,
826                         .data = data,
827                 },
828         };
829         struct perf_sample_data *sd;
830         int err;
831
832         if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(sds->sds))) {
833                 err = -EBUSY;
834                 goto out;
835         }
836
837         sd = &sds->sds[nest_level - 1];
838
839         if (unlikely(flags & ~(BPF_F_INDEX_MASK))) {
840                 err = -EINVAL;
841                 goto out;
842         }
843
844         perf_sample_data_init(sd, 0, 0);
845         sd->raw = &raw;
846
847         err = __bpf_perf_event_output(regs, map, flags, sd);
848
849 out:
850         this_cpu_dec(bpf_trace_nest_level);
851         return err;
852 }
853
854 static const struct bpf_func_proto bpf_perf_event_output_proto = {
855         .func           = bpf_perf_event_output,
856         .gpl_only       = true,
857         .ret_type       = RET_INTEGER,
858         .arg1_type      = ARG_PTR_TO_CTX,
859         .arg2_type      = ARG_CONST_MAP_PTR,
860         .arg3_type      = ARG_ANYTHING,
861         .arg4_type      = ARG_PTR_TO_MEM,
862         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
863 };
864
865 static DEFINE_PER_CPU(int, bpf_event_output_nest_level);
866 struct bpf_nested_pt_regs {
867         struct pt_regs regs[3];
868 };
869 static DEFINE_PER_CPU(struct bpf_nested_pt_regs, bpf_pt_regs);
870 static DEFINE_PER_CPU(struct bpf_trace_sample_data, bpf_misc_sds);
871
872 u64 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
873                      void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
874 {
875         int nest_level = this_cpu_inc_return(bpf_event_output_nest_level);
876         struct perf_raw_frag frag = {
877                 .copy           = ctx_copy,
878                 .size           = ctx_size,
879                 .data           = ctx,
880         };
881         struct perf_raw_record raw = {
882                 .frag = {
883                         {
884                                 .next   = ctx_size ? &frag : NULL,
885                         },
886                         .size   = meta_size,
887                         .data   = meta,
888                 },
889         };
890         struct perf_sample_data *sd;
891         struct pt_regs *regs;
892         u64 ret;
893
894         if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(bpf_misc_sds.sds))) {
895                 ret = -EBUSY;
896                 goto out;
897         }
898         sd = this_cpu_ptr(&bpf_misc_sds.sds[nest_level - 1]);
899         regs = this_cpu_ptr(&bpf_pt_regs.regs[nest_level - 1]);
900
901         perf_fetch_caller_regs(regs);
902         perf_sample_data_init(sd, 0, 0);
903         sd->raw = &raw;
904
905         ret = __bpf_perf_event_output(regs, map, flags, sd);
906 out:
907         this_cpu_dec(bpf_event_output_nest_level);
908         return ret;
909 }
910
911 BPF_CALL_0(bpf_get_current_task)
912 {
913         return (long) current;
914 }
915
916 const struct bpf_func_proto bpf_get_current_task_proto = {
917         .func           = bpf_get_current_task,
918         .gpl_only       = true,
919         .ret_type       = RET_INTEGER,
920 };
921
922 BPF_CALL_2(bpf_current_task_under_cgroup, struct bpf_map *, map, u32, idx)
923 {
924         struct bpf_array *array = container_of(map, struct bpf_array, map);
925         struct cgroup *cgrp;
926
927         if (unlikely(idx >= array->map.max_entries))
928                 return -E2BIG;
929
930         cgrp = READ_ONCE(array->ptrs[idx]);
931         if (unlikely(!cgrp))
932                 return -EAGAIN;
933
934         return task_under_cgroup_hierarchy(current, cgrp);
935 }
936
937 static const struct bpf_func_proto bpf_current_task_under_cgroup_proto = {
938         .func           = bpf_current_task_under_cgroup,
939         .gpl_only       = false,
940         .ret_type       = RET_INTEGER,
941         .arg1_type      = ARG_CONST_MAP_PTR,
942         .arg2_type      = ARG_ANYTHING,
943 };
944
945 struct send_signal_irq_work {
946         struct irq_work irq_work;
947         struct task_struct *task;
948         u32 sig;
949         enum pid_type type;
950 };
951
952 static DEFINE_PER_CPU(struct send_signal_irq_work, send_signal_work);
953
954 static void do_bpf_send_signal(struct irq_work *entry)
955 {
956         struct send_signal_irq_work *work;
957
958         work = container_of(entry, struct send_signal_irq_work, irq_work);
959         group_send_sig_info(work->sig, SEND_SIG_PRIV, work->task, work->type);
960 }
961
962 static int bpf_send_signal_common(u32 sig, enum pid_type type)
963 {
964         struct send_signal_irq_work *work = NULL;
965
966         /* Similar to bpf_probe_write_user, task needs to be
967          * in a sound condition and kernel memory access be
968          * permitted in order to send signal to the current
969          * task.
970          */
971         if (unlikely(current->flags & (PF_KTHREAD | PF_EXITING)))
972                 return -EPERM;
973         if (unlikely(uaccess_kernel()))
974                 return -EPERM;
975         if (unlikely(!nmi_uaccess_okay()))
976                 return -EPERM;
977
978         if (irqs_disabled()) {
979                 /* Do an early check on signal validity. Otherwise,
980                  * the error is lost in deferred irq_work.
981                  */
982                 if (unlikely(!valid_signal(sig)))
983                         return -EINVAL;
984
985                 work = this_cpu_ptr(&send_signal_work);
986                 if (atomic_read(&work->irq_work.flags) & IRQ_WORK_BUSY)
987                         return -EBUSY;
988
989                 /* Add the current task, which is the target of sending signal,
990                  * to the irq_work. The current task may change when queued
991                  * irq works get executed.
992                  */
993                 work->task = current;
994                 work->sig = sig;
995                 work->type = type;
996                 irq_work_queue(&work->irq_work);
997                 return 0;
998         }
999
1000         return group_send_sig_info(sig, SEND_SIG_PRIV, current, type);
1001 }
1002
1003 BPF_CALL_1(bpf_send_signal, u32, sig)
1004 {
1005         return bpf_send_signal_common(sig, PIDTYPE_TGID);
1006 }
1007
1008 static const struct bpf_func_proto bpf_send_signal_proto = {
1009         .func           = bpf_send_signal,
1010         .gpl_only       = false,
1011         .ret_type       = RET_INTEGER,
1012         .arg1_type      = ARG_ANYTHING,
1013 };
1014
1015 BPF_CALL_1(bpf_send_signal_thread, u32, sig)
1016 {
1017         return bpf_send_signal_common(sig, PIDTYPE_PID);
1018 }
1019
1020 static const struct bpf_func_proto bpf_send_signal_thread_proto = {
1021         .func           = bpf_send_signal_thread,
1022         .gpl_only       = false,
1023         .ret_type       = RET_INTEGER,
1024         .arg1_type      = ARG_ANYTHING,
1025 };
1026
1027 const struct bpf_func_proto *
1028 bpf_tracing_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1029 {
1030         switch (func_id) {
1031         case BPF_FUNC_map_lookup_elem:
1032                 return &bpf_map_lookup_elem_proto;
1033         case BPF_FUNC_map_update_elem:
1034                 return &bpf_map_update_elem_proto;
1035         case BPF_FUNC_map_delete_elem:
1036                 return &bpf_map_delete_elem_proto;
1037         case BPF_FUNC_map_push_elem:
1038                 return &bpf_map_push_elem_proto;
1039         case BPF_FUNC_map_pop_elem:
1040                 return &bpf_map_pop_elem_proto;
1041         case BPF_FUNC_map_peek_elem:
1042                 return &bpf_map_peek_elem_proto;
1043         case BPF_FUNC_ktime_get_ns:
1044                 return &bpf_ktime_get_ns_proto;
1045         case BPF_FUNC_ktime_get_boot_ns:
1046                 return &bpf_ktime_get_boot_ns_proto;
1047         case BPF_FUNC_tail_call:
1048                 return &bpf_tail_call_proto;
1049         case BPF_FUNC_get_current_pid_tgid:
1050                 return &bpf_get_current_pid_tgid_proto;
1051         case BPF_FUNC_get_current_task:
1052                 return &bpf_get_current_task_proto;
1053         case BPF_FUNC_get_current_uid_gid:
1054                 return &bpf_get_current_uid_gid_proto;
1055         case BPF_FUNC_get_current_comm:
1056                 return &bpf_get_current_comm_proto;
1057         case BPF_FUNC_trace_printk:
1058                 return bpf_get_trace_printk_proto();
1059         case BPF_FUNC_get_smp_processor_id:
1060                 return &bpf_get_smp_processor_id_proto;
1061         case BPF_FUNC_get_numa_node_id:
1062                 return &bpf_get_numa_node_id_proto;
1063         case BPF_FUNC_perf_event_read:
1064                 return &bpf_perf_event_read_proto;
1065         case BPF_FUNC_probe_write_user:
1066                 return bpf_get_probe_write_proto();
1067         case BPF_FUNC_current_task_under_cgroup:
1068                 return &bpf_current_task_under_cgroup_proto;
1069         case BPF_FUNC_get_prandom_u32:
1070                 return &bpf_get_prandom_u32_proto;
1071         case BPF_FUNC_probe_read_user:
1072                 return &bpf_probe_read_user_proto;
1073         case BPF_FUNC_probe_read_kernel:
1074                 return &bpf_probe_read_kernel_proto;
1075         case BPF_FUNC_probe_read_user_str:
1076                 return &bpf_probe_read_user_str_proto;
1077         case BPF_FUNC_probe_read_kernel_str:
1078                 return &bpf_probe_read_kernel_str_proto;
1079 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
1080         case BPF_FUNC_probe_read:
1081                 return &bpf_probe_read_compat_proto;
1082         case BPF_FUNC_probe_read_str:
1083                 return &bpf_probe_read_compat_str_proto;
1084 #endif
1085 #ifdef CONFIG_CGROUPS
1086         case BPF_FUNC_get_current_cgroup_id:
1087                 return &bpf_get_current_cgroup_id_proto;
1088 #endif
1089         case BPF_FUNC_send_signal:
1090                 return &bpf_send_signal_proto;
1091         case BPF_FUNC_send_signal_thread:
1092                 return &bpf_send_signal_thread_proto;
1093         case BPF_FUNC_perf_event_read_value:
1094                 return &bpf_perf_event_read_value_proto;
1095         case BPF_FUNC_get_ns_current_pid_tgid:
1096                 return &bpf_get_ns_current_pid_tgid_proto;
1097         case BPF_FUNC_ringbuf_output:
1098                 return &bpf_ringbuf_output_proto;
1099         case BPF_FUNC_ringbuf_reserve:
1100                 return &bpf_ringbuf_reserve_proto;
1101         case BPF_FUNC_ringbuf_submit:
1102                 return &bpf_ringbuf_submit_proto;
1103         case BPF_FUNC_ringbuf_discard:
1104                 return &bpf_ringbuf_discard_proto;
1105         case BPF_FUNC_ringbuf_query:
1106                 return &bpf_ringbuf_query_proto;
1107         default:
1108                 return NULL;
1109         }
1110 }
1111
1112 static const struct bpf_func_proto *
1113 kprobe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1114 {
1115         switch (func_id) {
1116         case BPF_FUNC_perf_event_output:
1117                 return &bpf_perf_event_output_proto;
1118         case BPF_FUNC_get_stackid:
1119                 return &bpf_get_stackid_proto;
1120         case BPF_FUNC_get_stack:
1121                 return &bpf_get_stack_proto;
1122 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
1123         case BPF_FUNC_override_return:
1124                 return &bpf_override_return_proto;
1125 #endif
1126         default:
1127                 return bpf_tracing_func_proto(func_id, prog);
1128         }
1129 }
1130
1131 /* bpf+kprobe programs can access fields of 'struct pt_regs' */
1132 static bool kprobe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1133                                         const struct bpf_prog *prog,
1134                                         struct bpf_insn_access_aux *info)
1135 {
1136         if (off < 0 || off >= sizeof(struct pt_regs))
1137                 return false;
1138         if (type != BPF_READ)
1139                 return false;
1140         if (off % size != 0)
1141                 return false;
1142         /*
1143          * Assertion for 32 bit to make sure last 8 byte access
1144          * (BPF_DW) to the last 4 byte member is disallowed.
1145          */
1146         if (off + size > sizeof(struct pt_regs))
1147                 return false;
1148
1149         return true;
1150 }
1151
1152 const struct bpf_verifier_ops kprobe_verifier_ops = {
1153         .get_func_proto  = kprobe_prog_func_proto,
1154         .is_valid_access = kprobe_prog_is_valid_access,
1155 };
1156
1157 const struct bpf_prog_ops kprobe_prog_ops = {
1158 };
1159
1160 BPF_CALL_5(bpf_perf_event_output_tp, void *, tp_buff, struct bpf_map *, map,
1161            u64, flags, void *, data, u64, size)
1162 {
1163         struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1164
1165         /*
1166          * r1 points to perf tracepoint buffer where first 8 bytes are hidden
1167          * from bpf program and contain a pointer to 'struct pt_regs'. Fetch it
1168          * from there and call the same bpf_perf_event_output() helper inline.
1169          */
1170         return ____bpf_perf_event_output(regs, map, flags, data, size);
1171 }
1172
1173 static const struct bpf_func_proto bpf_perf_event_output_proto_tp = {
1174         .func           = bpf_perf_event_output_tp,
1175         .gpl_only       = true,
1176         .ret_type       = RET_INTEGER,
1177         .arg1_type      = ARG_PTR_TO_CTX,
1178         .arg2_type      = ARG_CONST_MAP_PTR,
1179         .arg3_type      = ARG_ANYTHING,
1180         .arg4_type      = ARG_PTR_TO_MEM,
1181         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
1182 };
1183
1184 BPF_CALL_3(bpf_get_stackid_tp, void *, tp_buff, struct bpf_map *, map,
1185            u64, flags)
1186 {
1187         struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1188
1189         /*
1190          * Same comment as in bpf_perf_event_output_tp(), only that this time
1191          * the other helper's function body cannot be inlined due to being
1192          * external, thus we need to call raw helper function.
1193          */
1194         return bpf_get_stackid((unsigned long) regs, (unsigned long) map,
1195                                flags, 0, 0);
1196 }
1197
1198 static const struct bpf_func_proto bpf_get_stackid_proto_tp = {
1199         .func           = bpf_get_stackid_tp,
1200         .gpl_only       = true,
1201         .ret_type       = RET_INTEGER,
1202         .arg1_type      = ARG_PTR_TO_CTX,
1203         .arg2_type      = ARG_CONST_MAP_PTR,
1204         .arg3_type      = ARG_ANYTHING,
1205 };
1206
1207 BPF_CALL_4(bpf_get_stack_tp, void *, tp_buff, void *, buf, u32, size,
1208            u64, flags)
1209 {
1210         struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1211
1212         return bpf_get_stack((unsigned long) regs, (unsigned long) buf,
1213                              (unsigned long) size, flags, 0);
1214 }
1215
1216 static const struct bpf_func_proto bpf_get_stack_proto_tp = {
1217         .func           = bpf_get_stack_tp,
1218         .gpl_only       = true,
1219         .ret_type       = RET_INTEGER,
1220         .arg1_type      = ARG_PTR_TO_CTX,
1221         .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
1222         .arg3_type      = ARG_CONST_SIZE_OR_ZERO,
1223         .arg4_type      = ARG_ANYTHING,
1224 };
1225
1226 static const struct bpf_func_proto *
1227 tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1228 {
1229         switch (func_id) {
1230         case BPF_FUNC_perf_event_output:
1231                 return &bpf_perf_event_output_proto_tp;
1232         case BPF_FUNC_get_stackid:
1233                 return &bpf_get_stackid_proto_tp;
1234         case BPF_FUNC_get_stack:
1235                 return &bpf_get_stack_proto_tp;
1236         default:
1237                 return bpf_tracing_func_proto(func_id, prog);
1238         }
1239 }
1240
1241 static bool tp_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1242                                     const struct bpf_prog *prog,
1243                                     struct bpf_insn_access_aux *info)
1244 {
1245         if (off < sizeof(void *) || off >= PERF_MAX_TRACE_SIZE)
1246                 return false;
1247         if (type != BPF_READ)
1248                 return false;
1249         if (off % size != 0)
1250                 return false;
1251
1252         BUILD_BUG_ON(PERF_MAX_TRACE_SIZE % sizeof(__u64));
1253         return true;
1254 }
1255
1256 const struct bpf_verifier_ops tracepoint_verifier_ops = {
1257         .get_func_proto  = tp_prog_func_proto,
1258         .is_valid_access = tp_prog_is_valid_access,
1259 };
1260
1261 const struct bpf_prog_ops tracepoint_prog_ops = {
1262 };
1263
1264 BPF_CALL_3(bpf_perf_prog_read_value, struct bpf_perf_event_data_kern *, ctx,
1265            struct bpf_perf_event_value *, buf, u32, size)
1266 {
1267         int err = -EINVAL;
1268
1269         if (unlikely(size != sizeof(struct bpf_perf_event_value)))
1270                 goto clear;
1271         err = perf_event_read_local(ctx->event, &buf->counter, &buf->enabled,
1272                                     &buf->running);
1273         if (unlikely(err))
1274                 goto clear;
1275         return 0;
1276 clear:
1277         memset(buf, 0, size);
1278         return err;
1279 }
1280
1281 static const struct bpf_func_proto bpf_perf_prog_read_value_proto = {
1282          .func           = bpf_perf_prog_read_value,
1283          .gpl_only       = true,
1284          .ret_type       = RET_INTEGER,
1285          .arg1_type      = ARG_PTR_TO_CTX,
1286          .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
1287          .arg3_type      = ARG_CONST_SIZE,
1288 };
1289
1290 BPF_CALL_4(bpf_read_branch_records, struct bpf_perf_event_data_kern *, ctx,
1291            void *, buf, u32, size, u64, flags)
1292 {
1293 #ifndef CONFIG_X86
1294         return -ENOENT;
1295 #else
1296         static const u32 br_entry_size = sizeof(struct perf_branch_entry);
1297         struct perf_branch_stack *br_stack = ctx->data->br_stack;
1298         u32 to_copy;
1299
1300         if (unlikely(flags & ~BPF_F_GET_BRANCH_RECORDS_SIZE))
1301                 return -EINVAL;
1302
1303         if (unlikely(!br_stack))
1304                 return -EINVAL;
1305
1306         if (flags & BPF_F_GET_BRANCH_RECORDS_SIZE)
1307                 return br_stack->nr * br_entry_size;
1308
1309         if (!buf || (size % br_entry_size != 0))
1310                 return -EINVAL;
1311
1312         to_copy = min_t(u32, br_stack->nr * br_entry_size, size);
1313         memcpy(buf, br_stack->entries, to_copy);
1314
1315         return to_copy;
1316 #endif
1317 }
1318
1319 static const struct bpf_func_proto bpf_read_branch_records_proto = {
1320         .func           = bpf_read_branch_records,
1321         .gpl_only       = true,
1322         .ret_type       = RET_INTEGER,
1323         .arg1_type      = ARG_PTR_TO_CTX,
1324         .arg2_type      = ARG_PTR_TO_MEM_OR_NULL,
1325         .arg3_type      = ARG_CONST_SIZE_OR_ZERO,
1326         .arg4_type      = ARG_ANYTHING,
1327 };
1328
1329 static const struct bpf_func_proto *
1330 pe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1331 {
1332         switch (func_id) {
1333         case BPF_FUNC_perf_event_output:
1334                 return &bpf_perf_event_output_proto_tp;
1335         case BPF_FUNC_get_stackid:
1336                 return &bpf_get_stackid_proto_tp;
1337         case BPF_FUNC_get_stack:
1338                 return &bpf_get_stack_proto_tp;
1339         case BPF_FUNC_perf_prog_read_value:
1340                 return &bpf_perf_prog_read_value_proto;
1341         case BPF_FUNC_read_branch_records:
1342                 return &bpf_read_branch_records_proto;
1343         default:
1344                 return bpf_tracing_func_proto(func_id, prog);
1345         }
1346 }
1347
1348 /*
1349  * bpf_raw_tp_regs are separate from bpf_pt_regs used from skb/xdp
1350  * to avoid potential recursive reuse issue when/if tracepoints are added
1351  * inside bpf_*_event_output, bpf_get_stackid and/or bpf_get_stack.
1352  *
1353  * Since raw tracepoints run despite bpf_prog_active, support concurrent usage
1354  * in normal, irq, and nmi context.
1355  */
1356 struct bpf_raw_tp_regs {
1357         struct pt_regs regs[3];
1358 };
1359 static DEFINE_PER_CPU(struct bpf_raw_tp_regs, bpf_raw_tp_regs);
1360 static DEFINE_PER_CPU(int, bpf_raw_tp_nest_level);
1361 static struct pt_regs *get_bpf_raw_tp_regs(void)
1362 {
1363         struct bpf_raw_tp_regs *tp_regs = this_cpu_ptr(&bpf_raw_tp_regs);
1364         int nest_level = this_cpu_inc_return(bpf_raw_tp_nest_level);
1365
1366         if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(tp_regs->regs))) {
1367                 this_cpu_dec(bpf_raw_tp_nest_level);
1368                 return ERR_PTR(-EBUSY);
1369         }
1370
1371         return &tp_regs->regs[nest_level - 1];
1372 }
1373
1374 static void put_bpf_raw_tp_regs(void)
1375 {
1376         this_cpu_dec(bpf_raw_tp_nest_level);
1377 }
1378
1379 BPF_CALL_5(bpf_perf_event_output_raw_tp, struct bpf_raw_tracepoint_args *, args,
1380            struct bpf_map *, map, u64, flags, void *, data, u64, size)
1381 {
1382         struct pt_regs *regs = get_bpf_raw_tp_regs();
1383         int ret;
1384
1385         if (IS_ERR(regs))
1386                 return PTR_ERR(regs);
1387
1388         perf_fetch_caller_regs(regs);
1389         ret = ____bpf_perf_event_output(regs, map, flags, data, size);
1390
1391         put_bpf_raw_tp_regs();
1392         return ret;
1393 }
1394
1395 static const struct bpf_func_proto bpf_perf_event_output_proto_raw_tp = {
1396         .func           = bpf_perf_event_output_raw_tp,
1397         .gpl_only       = true,
1398         .ret_type       = RET_INTEGER,
1399         .arg1_type      = ARG_PTR_TO_CTX,
1400         .arg2_type      = ARG_CONST_MAP_PTR,
1401         .arg3_type      = ARG_ANYTHING,
1402         .arg4_type      = ARG_PTR_TO_MEM,
1403         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
1404 };
1405
1406 extern const struct bpf_func_proto bpf_skb_output_proto;
1407 extern const struct bpf_func_proto bpf_xdp_output_proto;
1408
1409 BPF_CALL_3(bpf_get_stackid_raw_tp, struct bpf_raw_tracepoint_args *, args,
1410            struct bpf_map *, map, u64, flags)
1411 {
1412         struct pt_regs *regs = get_bpf_raw_tp_regs();
1413         int ret;
1414
1415         if (IS_ERR(regs))
1416                 return PTR_ERR(regs);
1417
1418         perf_fetch_caller_regs(regs);
1419         /* similar to bpf_perf_event_output_tp, but pt_regs fetched differently */
1420         ret = bpf_get_stackid((unsigned long) regs, (unsigned long) map,
1421                               flags, 0, 0);
1422         put_bpf_raw_tp_regs();
1423         return ret;
1424 }
1425
1426 static const struct bpf_func_proto bpf_get_stackid_proto_raw_tp = {
1427         .func           = bpf_get_stackid_raw_tp,
1428         .gpl_only       = true,
1429         .ret_type       = RET_INTEGER,
1430         .arg1_type      = ARG_PTR_TO_CTX,
1431         .arg2_type      = ARG_CONST_MAP_PTR,
1432         .arg3_type      = ARG_ANYTHING,
1433 };
1434
1435 BPF_CALL_4(bpf_get_stack_raw_tp, struct bpf_raw_tracepoint_args *, args,
1436            void *, buf, u32, size, u64, flags)
1437 {
1438         struct pt_regs *regs = get_bpf_raw_tp_regs();
1439         int ret;
1440
1441         if (IS_ERR(regs))
1442                 return PTR_ERR(regs);
1443
1444         perf_fetch_caller_regs(regs);
1445         ret = bpf_get_stack((unsigned long) regs, (unsigned long) buf,
1446                             (unsigned long) size, flags, 0);
1447         put_bpf_raw_tp_regs();
1448         return ret;
1449 }
1450
1451 static const struct bpf_func_proto bpf_get_stack_proto_raw_tp = {
1452         .func           = bpf_get_stack_raw_tp,
1453         .gpl_only       = true,
1454         .ret_type       = RET_INTEGER,
1455         .arg1_type      = ARG_PTR_TO_CTX,
1456         .arg2_type      = ARG_PTR_TO_MEM,
1457         .arg3_type      = ARG_CONST_SIZE_OR_ZERO,
1458         .arg4_type      = ARG_ANYTHING,
1459 };
1460
1461 static const struct bpf_func_proto *
1462 raw_tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1463 {
1464         switch (func_id) {
1465         case BPF_FUNC_perf_event_output:
1466                 return &bpf_perf_event_output_proto_raw_tp;
1467         case BPF_FUNC_get_stackid:
1468                 return &bpf_get_stackid_proto_raw_tp;
1469         case BPF_FUNC_get_stack:
1470                 return &bpf_get_stack_proto_raw_tp;
1471         default:
1472                 return bpf_tracing_func_proto(func_id, prog);
1473         }
1474 }
1475
1476 const struct bpf_func_proto *
1477 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1478 {
1479         switch (func_id) {
1480 #ifdef CONFIG_NET
1481         case BPF_FUNC_skb_output:
1482                 return &bpf_skb_output_proto;
1483         case BPF_FUNC_xdp_output:
1484                 return &bpf_xdp_output_proto;
1485 #endif
1486         case BPF_FUNC_seq_printf:
1487                 return prog->expected_attach_type == BPF_TRACE_ITER ?
1488                        &bpf_seq_printf_proto :
1489                        NULL;
1490         case BPF_FUNC_seq_write:
1491                 return prog->expected_attach_type == BPF_TRACE_ITER ?
1492                        &bpf_seq_write_proto :
1493                        NULL;
1494         default:
1495                 return raw_tp_prog_func_proto(func_id, prog);
1496         }
1497 }
1498
1499 static bool raw_tp_prog_is_valid_access(int off, int size,
1500                                         enum bpf_access_type type,
1501                                         const struct bpf_prog *prog,
1502                                         struct bpf_insn_access_aux *info)
1503 {
1504         if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
1505                 return false;
1506         if (type != BPF_READ)
1507                 return false;
1508         if (off % size != 0)
1509                 return false;
1510         return true;
1511 }
1512
1513 static bool tracing_prog_is_valid_access(int off, int size,
1514                                          enum bpf_access_type type,
1515                                          const struct bpf_prog *prog,
1516                                          struct bpf_insn_access_aux *info)
1517 {
1518         if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
1519                 return false;
1520         if (type != BPF_READ)
1521                 return false;
1522         if (off % size != 0)
1523                 return false;
1524         return btf_ctx_access(off, size, type, prog, info);
1525 }
1526
1527 int __weak bpf_prog_test_run_tracing(struct bpf_prog *prog,
1528                                      const union bpf_attr *kattr,
1529                                      union bpf_attr __user *uattr)
1530 {
1531         return -ENOTSUPP;
1532 }
1533
1534 const struct bpf_verifier_ops raw_tracepoint_verifier_ops = {
1535         .get_func_proto  = raw_tp_prog_func_proto,
1536         .is_valid_access = raw_tp_prog_is_valid_access,
1537 };
1538
1539 const struct bpf_prog_ops raw_tracepoint_prog_ops = {
1540 };
1541
1542 const struct bpf_verifier_ops tracing_verifier_ops = {
1543         .get_func_proto  = tracing_prog_func_proto,
1544         .is_valid_access = tracing_prog_is_valid_access,
1545 };
1546
1547 const struct bpf_prog_ops tracing_prog_ops = {
1548         .test_run = bpf_prog_test_run_tracing,
1549 };
1550
1551 static bool raw_tp_writable_prog_is_valid_access(int off, int size,
1552                                                  enum bpf_access_type type,
1553                                                  const struct bpf_prog *prog,
1554                                                  struct bpf_insn_access_aux *info)
1555 {
1556         if (off == 0) {
1557                 if (size != sizeof(u64) || type != BPF_READ)
1558                         return false;
1559                 info->reg_type = PTR_TO_TP_BUFFER;
1560         }
1561         return raw_tp_prog_is_valid_access(off, size, type, prog, info);
1562 }
1563
1564 const struct bpf_verifier_ops raw_tracepoint_writable_verifier_ops = {
1565         .get_func_proto  = raw_tp_prog_func_proto,
1566         .is_valid_access = raw_tp_writable_prog_is_valid_access,
1567 };
1568
1569 const struct bpf_prog_ops raw_tracepoint_writable_prog_ops = {
1570 };
1571
1572 static bool pe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1573                                     const struct bpf_prog *prog,
1574                                     struct bpf_insn_access_aux *info)
1575 {
1576         const int size_u64 = sizeof(u64);
1577
1578         if (off < 0 || off >= sizeof(struct bpf_perf_event_data))
1579                 return false;
1580         if (type != BPF_READ)
1581                 return false;
1582         if (off % size != 0) {
1583                 if (sizeof(unsigned long) != 4)
1584                         return false;
1585                 if (size != 8)
1586                         return false;
1587                 if (off % size != 4)
1588                         return false;
1589         }
1590
1591         switch (off) {
1592         case bpf_ctx_range(struct bpf_perf_event_data, sample_period):
1593                 bpf_ctx_record_field_size(info, size_u64);
1594                 if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
1595                         return false;
1596                 break;
1597         case bpf_ctx_range(struct bpf_perf_event_data, addr):
1598                 bpf_ctx_record_field_size(info, size_u64);
1599                 if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
1600                         return false;
1601                 break;
1602         default:
1603                 if (size != sizeof(long))
1604                         return false;
1605         }
1606
1607         return true;
1608 }
1609
1610 static u32 pe_prog_convert_ctx_access(enum bpf_access_type type,
1611                                       const struct bpf_insn *si,
1612                                       struct bpf_insn *insn_buf,
1613                                       struct bpf_prog *prog, u32 *target_size)
1614 {
1615         struct bpf_insn *insn = insn_buf;
1616
1617         switch (si->off) {
1618         case offsetof(struct bpf_perf_event_data, sample_period):
1619                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
1620                                                        data), si->dst_reg, si->src_reg,
1621                                       offsetof(struct bpf_perf_event_data_kern, data));
1622                 *insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
1623                                       bpf_target_off(struct perf_sample_data, period, 8,
1624                                                      target_size));
1625                 break;
1626         case offsetof(struct bpf_perf_event_data, addr):
1627                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
1628                                                        data), si->dst_reg, si->src_reg,
1629                                       offsetof(struct bpf_perf_event_data_kern, data));
1630                 *insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
1631                                       bpf_target_off(struct perf_sample_data, addr, 8,
1632                                                      target_size));
1633                 break;
1634         default:
1635                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
1636                                                        regs), si->dst_reg, si->src_reg,
1637                                       offsetof(struct bpf_perf_event_data_kern, regs));
1638                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(long), si->dst_reg, si->dst_reg,
1639                                       si->off);
1640                 break;
1641         }
1642
1643         return insn - insn_buf;
1644 }
1645
1646 const struct bpf_verifier_ops perf_event_verifier_ops = {
1647         .get_func_proto         = pe_prog_func_proto,
1648         .is_valid_access        = pe_prog_is_valid_access,
1649         .convert_ctx_access     = pe_prog_convert_ctx_access,
1650 };
1651
1652 const struct bpf_prog_ops perf_event_prog_ops = {
1653 };
1654
1655 static DEFINE_MUTEX(bpf_event_mutex);
1656
1657 #define BPF_TRACE_MAX_PROGS 64
1658
1659 int perf_event_attach_bpf_prog(struct perf_event *event,
1660                                struct bpf_prog *prog)
1661 {
1662         struct bpf_prog_array *old_array;
1663         struct bpf_prog_array *new_array;
1664         int ret = -EEXIST;
1665
1666         /*
1667          * Kprobe override only works if they are on the function entry,
1668          * and only if they are on the opt-in list.
1669          */
1670         if (prog->kprobe_override &&
1671             (!trace_kprobe_on_func_entry(event->tp_event) ||
1672              !trace_kprobe_error_injectable(event->tp_event)))
1673                 return -EINVAL;
1674
1675         mutex_lock(&bpf_event_mutex);
1676
1677         if (event->prog)
1678                 goto unlock;
1679
1680         old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
1681         if (old_array &&
1682             bpf_prog_array_length(old_array) >= BPF_TRACE_MAX_PROGS) {
1683                 ret = -E2BIG;
1684                 goto unlock;
1685         }
1686
1687         ret = bpf_prog_array_copy(old_array, NULL, prog, &new_array);
1688         if (ret < 0)
1689                 goto unlock;
1690
1691         /* set the new array to event->tp_event and set event->prog */
1692         event->prog = prog;
1693         rcu_assign_pointer(event->tp_event->prog_array, new_array);
1694         bpf_prog_array_free(old_array);
1695
1696 unlock:
1697         mutex_unlock(&bpf_event_mutex);
1698         return ret;
1699 }
1700
1701 void perf_event_detach_bpf_prog(struct perf_event *event)
1702 {
1703         struct bpf_prog_array *old_array;
1704         struct bpf_prog_array *new_array;
1705         int ret;
1706
1707         mutex_lock(&bpf_event_mutex);
1708
1709         if (!event->prog)
1710                 goto unlock;
1711
1712         old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
1713         ret = bpf_prog_array_copy(old_array, event->prog, NULL, &new_array);
1714         if (ret == -ENOENT)
1715                 goto unlock;
1716         if (ret < 0) {
1717                 bpf_prog_array_delete_safe(old_array, event->prog);
1718         } else {
1719                 rcu_assign_pointer(event->tp_event->prog_array, new_array);
1720                 bpf_prog_array_free(old_array);
1721         }
1722
1723         bpf_prog_put(event->prog);
1724         event->prog = NULL;
1725
1726 unlock:
1727         mutex_unlock(&bpf_event_mutex);
1728 }
1729
1730 int perf_event_query_prog_array(struct perf_event *event, void __user *info)
1731 {
1732         struct perf_event_query_bpf __user *uquery = info;
1733         struct perf_event_query_bpf query = {};
1734         struct bpf_prog_array *progs;
1735         u32 *ids, prog_cnt, ids_len;
1736         int ret;
1737
1738         if (!perfmon_capable())
1739                 return -EPERM;
1740         if (event->attr.type != PERF_TYPE_TRACEPOINT)
1741                 return -EINVAL;
1742         if (copy_from_user(&query, uquery, sizeof(query)))
1743                 return -EFAULT;
1744
1745         ids_len = query.ids_len;
1746         if (ids_len > BPF_TRACE_MAX_PROGS)
1747                 return -E2BIG;
1748         ids = kcalloc(ids_len, sizeof(u32), GFP_USER | __GFP_NOWARN);
1749         if (!ids)
1750                 return -ENOMEM;
1751         /*
1752          * The above kcalloc returns ZERO_SIZE_PTR when ids_len = 0, which
1753          * is required when user only wants to check for uquery->prog_cnt.
1754          * There is no need to check for it since the case is handled
1755          * gracefully in bpf_prog_array_copy_info.
1756          */
1757
1758         mutex_lock(&bpf_event_mutex);
1759         progs = bpf_event_rcu_dereference(event->tp_event->prog_array);
1760         ret = bpf_prog_array_copy_info(progs, ids, ids_len, &prog_cnt);
1761         mutex_unlock(&bpf_event_mutex);
1762
1763         if (copy_to_user(&uquery->prog_cnt, &prog_cnt, sizeof(prog_cnt)) ||
1764             copy_to_user(uquery->ids, ids, ids_len * sizeof(u32)))
1765                 ret = -EFAULT;
1766
1767         kfree(ids);
1768         return ret;
1769 }
1770
1771 extern struct bpf_raw_event_map __start__bpf_raw_tp[];
1772 extern struct bpf_raw_event_map __stop__bpf_raw_tp[];
1773
1774 struct bpf_raw_event_map *bpf_get_raw_tracepoint(const char *name)
1775 {
1776         struct bpf_raw_event_map *btp = __start__bpf_raw_tp;
1777
1778         for (; btp < __stop__bpf_raw_tp; btp++) {
1779                 if (!strcmp(btp->tp->name, name))
1780                         return btp;
1781         }
1782
1783         return bpf_get_raw_tracepoint_module(name);
1784 }
1785
1786 void bpf_put_raw_tracepoint(struct bpf_raw_event_map *btp)
1787 {
1788         struct module *mod = __module_address((unsigned long)btp);
1789
1790         if (mod)
1791                 module_put(mod);
1792 }
1793
1794 static __always_inline
1795 void __bpf_trace_run(struct bpf_prog *prog, u64 *args)
1796 {
1797         cant_sleep();
1798         rcu_read_lock();
1799         (void) BPF_PROG_RUN(prog, args);
1800         rcu_read_unlock();
1801 }
1802
1803 #define UNPACK(...)                     __VA_ARGS__
1804 #define REPEAT_1(FN, DL, X, ...)        FN(X)
1805 #define REPEAT_2(FN, DL, X, ...)        FN(X) UNPACK DL REPEAT_1(FN, DL, __VA_ARGS__)
1806 #define REPEAT_3(FN, DL, X, ...)        FN(X) UNPACK DL REPEAT_2(FN, DL, __VA_ARGS__)
1807 #define REPEAT_4(FN, DL, X, ...)        FN(X) UNPACK DL REPEAT_3(FN, DL, __VA_ARGS__)
1808 #define REPEAT_5(FN, DL, X, ...)        FN(X) UNPACK DL REPEAT_4(FN, DL, __VA_ARGS__)
1809 #define REPEAT_6(FN, DL, X, ...)        FN(X) UNPACK DL REPEAT_5(FN, DL, __VA_ARGS__)
1810 #define REPEAT_7(FN, DL, X, ...)        FN(X) UNPACK DL REPEAT_6(FN, DL, __VA_ARGS__)
1811 #define REPEAT_8(FN, DL, X, ...)        FN(X) UNPACK DL REPEAT_7(FN, DL, __VA_ARGS__)
1812 #define REPEAT_9(FN, DL, X, ...)        FN(X) UNPACK DL REPEAT_8(FN, DL, __VA_ARGS__)
1813 #define REPEAT_10(FN, DL, X, ...)       FN(X) UNPACK DL REPEAT_9(FN, DL, __VA_ARGS__)
1814 #define REPEAT_11(FN, DL, X, ...)       FN(X) UNPACK DL REPEAT_10(FN, DL, __VA_ARGS__)
1815 #define REPEAT_12(FN, DL, X, ...)       FN(X) UNPACK DL REPEAT_11(FN, DL, __VA_ARGS__)
1816 #define REPEAT(X, FN, DL, ...)          REPEAT_##X(FN, DL, __VA_ARGS__)
1817
1818 #define SARG(X)         u64 arg##X
1819 #define COPY(X)         args[X] = arg##X
1820
1821 #define __DL_COM        (,)
1822 #define __DL_SEM        (;)
1823
1824 #define __SEQ_0_11      0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
1825
1826 #define BPF_TRACE_DEFN_x(x)                                             \
1827         void bpf_trace_run##x(struct bpf_prog *prog,                    \
1828                               REPEAT(x, SARG, __DL_COM, __SEQ_0_11))    \
1829         {                                                               \
1830                 u64 args[x];                                            \
1831                 REPEAT(x, COPY, __DL_SEM, __SEQ_0_11);                  \
1832                 __bpf_trace_run(prog, args);                            \
1833         }                                                               \
1834         EXPORT_SYMBOL_GPL(bpf_trace_run##x)
1835 BPF_TRACE_DEFN_x(1);
1836 BPF_TRACE_DEFN_x(2);
1837 BPF_TRACE_DEFN_x(3);
1838 BPF_TRACE_DEFN_x(4);
1839 BPF_TRACE_DEFN_x(5);
1840 BPF_TRACE_DEFN_x(6);
1841 BPF_TRACE_DEFN_x(7);
1842 BPF_TRACE_DEFN_x(8);
1843 BPF_TRACE_DEFN_x(9);
1844 BPF_TRACE_DEFN_x(10);
1845 BPF_TRACE_DEFN_x(11);
1846 BPF_TRACE_DEFN_x(12);
1847
1848 static int __bpf_probe_register(struct bpf_raw_event_map *btp, struct bpf_prog *prog)
1849 {
1850         struct tracepoint *tp = btp->tp;
1851
1852         /*
1853          * check that program doesn't access arguments beyond what's
1854          * available in this tracepoint
1855          */
1856         if (prog->aux->max_ctx_offset > btp->num_args * sizeof(u64))
1857                 return -EINVAL;
1858
1859         if (prog->aux->max_tp_access > btp->writable_size)
1860                 return -EINVAL;
1861
1862         return tracepoint_probe_register(tp, (void *)btp->bpf_func, prog);
1863 }
1864
1865 int bpf_probe_register(struct bpf_raw_event_map *btp, struct bpf_prog *prog)
1866 {
1867         return __bpf_probe_register(btp, prog);
1868 }
1869
1870 int bpf_probe_unregister(struct bpf_raw_event_map *btp, struct bpf_prog *prog)
1871 {
1872         return tracepoint_probe_unregister(btp->tp, (void *)btp->bpf_func, prog);
1873 }
1874
1875 int bpf_get_perf_event_info(const struct perf_event *event, u32 *prog_id,
1876                             u32 *fd_type, const char **buf,
1877                             u64 *probe_offset, u64 *probe_addr)
1878 {
1879         bool is_tracepoint, is_syscall_tp;
1880         struct bpf_prog *prog;
1881         int flags, err = 0;
1882
1883         prog = event->prog;
1884         if (!prog)
1885                 return -ENOENT;
1886
1887         /* not supporting BPF_PROG_TYPE_PERF_EVENT yet */
1888         if (prog->type == BPF_PROG_TYPE_PERF_EVENT)
1889                 return -EOPNOTSUPP;
1890
1891         *prog_id = prog->aux->id;
1892         flags = event->tp_event->flags;
1893         is_tracepoint = flags & TRACE_EVENT_FL_TRACEPOINT;
1894         is_syscall_tp = is_syscall_trace_event(event->tp_event);
1895
1896         if (is_tracepoint || is_syscall_tp) {
1897                 *buf = is_tracepoint ? event->tp_event->tp->name
1898                                      : event->tp_event->name;
1899                 *fd_type = BPF_FD_TYPE_TRACEPOINT;
1900                 *probe_offset = 0x0;
1901                 *probe_addr = 0x0;
1902         } else {
1903                 /* kprobe/uprobe */
1904                 err = -EOPNOTSUPP;
1905 #ifdef CONFIG_KPROBE_EVENTS
1906                 if (flags & TRACE_EVENT_FL_KPROBE)
1907                         err = bpf_get_kprobe_info(event, fd_type, buf,
1908                                                   probe_offset, probe_addr,
1909                                                   event->attr.type == PERF_TYPE_TRACEPOINT);
1910 #endif
1911 #ifdef CONFIG_UPROBE_EVENTS
1912                 if (flags & TRACE_EVENT_FL_UPROBE)
1913                         err = bpf_get_uprobe_info(event, fd_type, buf,
1914                                                   probe_offset,
1915                                                   event->attr.type == PERF_TYPE_TRACEPOINT);
1916 #endif
1917         }
1918
1919         return err;
1920 }
1921
1922 static int __init send_signal_irq_work_init(void)
1923 {
1924         int cpu;
1925         struct send_signal_irq_work *work;
1926
1927         for_each_possible_cpu(cpu) {
1928                 work = per_cpu_ptr(&send_signal_work, cpu);
1929                 init_irq_work(&work->irq_work, do_bpf_send_signal);
1930         }
1931         return 0;
1932 }
1933
1934 subsys_initcall(send_signal_irq_work_init);
1935
1936 #ifdef CONFIG_MODULES
1937 static int bpf_event_notify(struct notifier_block *nb, unsigned long op,
1938                             void *module)
1939 {
1940         struct bpf_trace_module *btm, *tmp;
1941         struct module *mod = module;
1942
1943         if (mod->num_bpf_raw_events == 0 ||
1944             (op != MODULE_STATE_COMING && op != MODULE_STATE_GOING))
1945                 return 0;
1946
1947         mutex_lock(&bpf_module_mutex);
1948
1949         switch (op) {
1950         case MODULE_STATE_COMING:
1951                 btm = kzalloc(sizeof(*btm), GFP_KERNEL);
1952                 if (btm) {
1953                         btm->module = module;
1954                         list_add(&btm->list, &bpf_trace_modules);
1955                 }
1956                 break;
1957         case MODULE_STATE_GOING:
1958                 list_for_each_entry_safe(btm, tmp, &bpf_trace_modules, list) {
1959                         if (btm->module == module) {
1960                                 list_del(&btm->list);
1961                                 kfree(btm);
1962                                 break;
1963                         }
1964                 }
1965                 break;
1966         }
1967
1968         mutex_unlock(&bpf_module_mutex);
1969
1970         return 0;
1971 }
1972
1973 static struct notifier_block bpf_module_nb = {
1974         .notifier_call = bpf_event_notify,
1975 };
1976
1977 static int __init bpf_event_init(void)
1978 {
1979         register_module_notifier(&bpf_module_nb);
1980         return 0;
1981 }
1982
1983 fs_initcall(bpf_event_init);
1984 #endif /* CONFIG_MODULES */