GNU Linux-libre 4.19.264-gnu1
[releases.git] / kernel / trace / trace_uprobe.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * uprobes-based tracing events
4  *
5  * Copyright (C) IBM Corporation, 2010-2012
6  * Author:      Srikar Dronamraju <srikar@linux.vnet.ibm.com>
7  */
8 #define pr_fmt(fmt)     "trace_uprobe: " fmt
9
10 #include <linux/module.h>
11 #include <linux/uaccess.h>
12 #include <linux/uprobes.h>
13 #include <linux/namei.h>
14 #include <linux/string.h>
15 #include <linux/rculist.h>
16
17 #include "trace_probe.h"
18
19 #define UPROBE_EVENT_SYSTEM     "uprobes"
20
21 struct uprobe_trace_entry_head {
22         struct trace_entry      ent;
23         unsigned long           vaddr[];
24 };
25
26 #define SIZEOF_TRACE_ENTRY(is_return)                   \
27         (sizeof(struct uprobe_trace_entry_head) +       \
28          sizeof(unsigned long) * (is_return ? 2 : 1))
29
30 #define DATAOF_TRACE_ENTRY(entry, is_return)            \
31         ((void*)(entry) + SIZEOF_TRACE_ENTRY(is_return))
32
33 struct trace_uprobe_filter {
34         rwlock_t                rwlock;
35         int                     nr_systemwide;
36         struct list_head        perf_events;
37 };
38
39 /*
40  * uprobe event core functions
41  */
42 struct trace_uprobe {
43         struct list_head                list;
44         struct trace_uprobe_filter      filter;
45         struct uprobe_consumer          consumer;
46         struct path                     path;
47         struct inode                    *inode;
48         char                            *filename;
49         unsigned long                   offset;
50         unsigned long                   nhit;
51         struct trace_probe              tp;
52 };
53
54 #define SIZEOF_TRACE_UPROBE(n)                          \
55         (offsetof(struct trace_uprobe, tp.args) +       \
56         (sizeof(struct probe_arg) * (n)))
57
58 static int register_uprobe_event(struct trace_uprobe *tu);
59 static int unregister_uprobe_event(struct trace_uprobe *tu);
60
61 static DEFINE_MUTEX(uprobe_lock);
62 static LIST_HEAD(uprobe_list);
63
64 struct uprobe_dispatch_data {
65         struct trace_uprobe     *tu;
66         unsigned long           bp_addr;
67 };
68
69 static int uprobe_dispatcher(struct uprobe_consumer *con, struct pt_regs *regs);
70 static int uretprobe_dispatcher(struct uprobe_consumer *con,
71                                 unsigned long func, struct pt_regs *regs);
72
73 #ifdef CONFIG_STACK_GROWSUP
74 static unsigned long adjust_stack_addr(unsigned long addr, unsigned int n)
75 {
76         return addr - (n * sizeof(long));
77 }
78 #else
79 static unsigned long adjust_stack_addr(unsigned long addr, unsigned int n)
80 {
81         return addr + (n * sizeof(long));
82 }
83 #endif
84
85 static unsigned long get_user_stack_nth(struct pt_regs *regs, unsigned int n)
86 {
87         unsigned long ret;
88         unsigned long addr = user_stack_pointer(regs);
89
90         addr = adjust_stack_addr(addr, n);
91
92         if (copy_from_user(&ret, (void __force __user *) addr, sizeof(ret)))
93                 return 0;
94
95         return ret;
96 }
97
98 /*
99  * Uprobes-specific fetch functions
100  */
101 #define DEFINE_FETCH_stack(type)                                        \
102 static void FETCH_FUNC_NAME(stack, type)(struct pt_regs *regs,          \
103                                          void *offset, void *dest)      \
104 {                                                                       \
105         *(type *)dest = (type)get_user_stack_nth(regs,                  \
106                                               ((unsigned long)offset)); \
107 }
108 DEFINE_BASIC_FETCH_FUNCS(stack)
109 /* No string on the stack entry */
110 #define fetch_stack_string      NULL
111 #define fetch_stack_string_size NULL
112
113 #define DEFINE_FETCH_memory(type)                                       \
114 static void FETCH_FUNC_NAME(memory, type)(struct pt_regs *regs,         \
115                                           void *addr, void *dest)       \
116 {                                                                       \
117         type retval;                                                    \
118         void __user *vaddr = (void __force __user *) addr;              \
119                                                                         \
120         if (copy_from_user(&retval, vaddr, sizeof(type)))               \
121                 *(type *)dest = 0;                                      \
122         else                                                            \
123                 *(type *) dest = retval;                                \
124 }
125 DEFINE_BASIC_FETCH_FUNCS(memory)
126 /*
127  * Fetch a null-terminated string. Caller MUST set *(u32 *)dest with max
128  * length and relative data location.
129  */
130 static void FETCH_FUNC_NAME(memory, string)(struct pt_regs *regs,
131                                             void *addr, void *dest)
132 {
133         long ret;
134         u32 rloc = *(u32 *)dest;
135         int maxlen  = get_rloc_len(rloc);
136         u8 *dst = get_rloc_data(dest);
137         void __user *src = (void __force __user *) addr;
138
139         if (!maxlen)
140                 return;
141
142         ret = strncpy_from_user(dst, src, maxlen);
143         if (ret == maxlen)
144                 dst[ret - 1] = '\0';
145         else if (ret >= 0)
146                 /*
147                  * Include the terminating null byte. In this case it
148                  * was copied by strncpy_from_user but not accounted
149                  * for in ret.
150                  */
151                 ret++;
152
153         if (ret < 0) {  /* Failed to fetch string */
154                 ((u8 *)get_rloc_data(dest))[0] = '\0';
155                 *(u32 *)dest = make_data_rloc(0, get_rloc_offs(rloc));
156         } else {
157                 *(u32 *)dest = make_data_rloc(ret, get_rloc_offs(rloc));
158         }
159 }
160
161 static void FETCH_FUNC_NAME(memory, string_size)(struct pt_regs *regs,
162                                                  void *addr, void *dest)
163 {
164         int len;
165         void __user *vaddr = (void __force __user *) addr;
166
167         len = strnlen_user(vaddr, MAX_STRING_SIZE);
168
169         if (len == 0 || len > MAX_STRING_SIZE)  /* Failed to check length */
170                 *(u32 *)dest = 0;
171         else
172                 *(u32 *)dest = len;
173 }
174
175 static unsigned long translate_user_vaddr(void *file_offset)
176 {
177         unsigned long base_addr;
178         struct uprobe_dispatch_data *udd;
179
180         udd = (void *) current->utask->vaddr;
181
182         base_addr = udd->bp_addr - udd->tu->offset;
183         return base_addr + (unsigned long)file_offset;
184 }
185
186 #define DEFINE_FETCH_file_offset(type)                                  \
187 static void FETCH_FUNC_NAME(file_offset, type)(struct pt_regs *regs,    \
188                                                void *offset, void *dest)\
189 {                                                                       \
190         void *vaddr = (void *)translate_user_vaddr(offset);             \
191                                                                         \
192         FETCH_FUNC_NAME(memory, type)(regs, vaddr, dest);               \
193 }
194 DEFINE_BASIC_FETCH_FUNCS(file_offset)
195 DEFINE_FETCH_file_offset(string)
196 DEFINE_FETCH_file_offset(string_size)
197
198 /* Fetch type information table */
199 static const struct fetch_type uprobes_fetch_type_table[] = {
200         /* Special types */
201         [FETCH_TYPE_STRING] = __ASSIGN_FETCH_TYPE("string", string, string,
202                                         sizeof(u32), 1, "__data_loc char[]"),
203         [FETCH_TYPE_STRSIZE] = __ASSIGN_FETCH_TYPE("string_size", u32,
204                                         string_size, sizeof(u32), 0, "u32"),
205         /* Basic types */
206         ASSIGN_FETCH_TYPE(u8,  u8,  0),
207         ASSIGN_FETCH_TYPE(u16, u16, 0),
208         ASSIGN_FETCH_TYPE(u32, u32, 0),
209         ASSIGN_FETCH_TYPE(u64, u64, 0),
210         ASSIGN_FETCH_TYPE(s8,  u8,  1),
211         ASSIGN_FETCH_TYPE(s16, u16, 1),
212         ASSIGN_FETCH_TYPE(s32, u32, 1),
213         ASSIGN_FETCH_TYPE(s64, u64, 1),
214         ASSIGN_FETCH_TYPE_ALIAS(x8,  u8,  u8,  0),
215         ASSIGN_FETCH_TYPE_ALIAS(x16, u16, u16, 0),
216         ASSIGN_FETCH_TYPE_ALIAS(x32, u32, u32, 0),
217         ASSIGN_FETCH_TYPE_ALIAS(x64, u64, u64, 0),
218
219         ASSIGN_FETCH_TYPE_END
220 };
221
222 static inline void init_trace_uprobe_filter(struct trace_uprobe_filter *filter)
223 {
224         rwlock_init(&filter->rwlock);
225         filter->nr_systemwide = 0;
226         INIT_LIST_HEAD(&filter->perf_events);
227 }
228
229 static inline bool uprobe_filter_is_empty(struct trace_uprobe_filter *filter)
230 {
231         return !filter->nr_systemwide && list_empty(&filter->perf_events);
232 }
233
234 static inline bool is_ret_probe(struct trace_uprobe *tu)
235 {
236         return tu->consumer.ret_handler != NULL;
237 }
238
239 /*
240  * Allocate new trace_uprobe and initialize it (including uprobes).
241  */
242 static struct trace_uprobe *
243 alloc_trace_uprobe(const char *group, const char *event, int nargs, bool is_ret)
244 {
245         struct trace_uprobe *tu;
246
247         if (!event || !is_good_name(event))
248                 return ERR_PTR(-EINVAL);
249
250         if (!group || !is_good_name(group))
251                 return ERR_PTR(-EINVAL);
252
253         tu = kzalloc(SIZEOF_TRACE_UPROBE(nargs), GFP_KERNEL);
254         if (!tu)
255                 return ERR_PTR(-ENOMEM);
256
257         tu->tp.call.class = &tu->tp.class;
258         tu->tp.call.name = kstrdup(event, GFP_KERNEL);
259         if (!tu->tp.call.name)
260                 goto error;
261
262         tu->tp.class.system = kstrdup(group, GFP_KERNEL);
263         if (!tu->tp.class.system)
264                 goto error;
265
266         INIT_LIST_HEAD(&tu->list);
267         INIT_LIST_HEAD(&tu->tp.files);
268         tu->consumer.handler = uprobe_dispatcher;
269         if (is_ret)
270                 tu->consumer.ret_handler = uretprobe_dispatcher;
271         init_trace_uprobe_filter(&tu->filter);
272         return tu;
273
274 error:
275         kfree(tu->tp.call.name);
276         kfree(tu);
277
278         return ERR_PTR(-ENOMEM);
279 }
280
281 static void free_trace_uprobe(struct trace_uprobe *tu)
282 {
283         int i;
284
285         for (i = 0; i < tu->tp.nr_args; i++)
286                 traceprobe_free_probe_arg(&tu->tp.args[i]);
287
288         path_put(&tu->path);
289         kfree(tu->tp.call.class->system);
290         kfree(tu->tp.call.name);
291         kfree(tu->filename);
292         kfree(tu);
293 }
294
295 static struct trace_uprobe *find_probe_event(const char *event, const char *group)
296 {
297         struct trace_uprobe *tu;
298
299         list_for_each_entry(tu, &uprobe_list, list)
300                 if (strcmp(trace_event_name(&tu->tp.call), event) == 0 &&
301                     strcmp(tu->tp.call.class->system, group) == 0)
302                         return tu;
303
304         return NULL;
305 }
306
307 /* Unregister a trace_uprobe and probe_event: call with locking uprobe_lock */
308 static int unregister_trace_uprobe(struct trace_uprobe *tu)
309 {
310         int ret;
311
312         ret = unregister_uprobe_event(tu);
313         if (ret)
314                 return ret;
315
316         list_del(&tu->list);
317         free_trace_uprobe(tu);
318         return 0;
319 }
320
321 /* Register a trace_uprobe and probe_event */
322 static int register_trace_uprobe(struct trace_uprobe *tu)
323 {
324         struct trace_uprobe *old_tu;
325         int ret;
326
327         mutex_lock(&uprobe_lock);
328
329         /* register as an event */
330         old_tu = find_probe_event(trace_event_name(&tu->tp.call),
331                         tu->tp.call.class->system);
332         if (old_tu) {
333                 /* delete old event */
334                 ret = unregister_trace_uprobe(old_tu);
335                 if (ret)
336                         goto end;
337         }
338
339         ret = register_uprobe_event(tu);
340         if (ret) {
341                 pr_warn("Failed to register probe event(%d)\n", ret);
342                 goto end;
343         }
344
345         list_add_tail(&tu->list, &uprobe_list);
346
347 end:
348         mutex_unlock(&uprobe_lock);
349
350         return ret;
351 }
352
353 /*
354  * Argument syntax:
355  *  - Add uprobe: p|r[:[GRP/]EVENT] PATH:OFFSET [FETCHARGS]
356  *
357  *  - Remove uprobe: -:[GRP/]EVENT
358  */
359 static int create_trace_uprobe(int argc, char **argv)
360 {
361         struct trace_uprobe *tu;
362         char *arg, *event, *group, *filename;
363         char buf[MAX_EVENT_NAME_LEN];
364         struct path path;
365         unsigned long offset;
366         bool is_delete, is_return;
367         int i, ret;
368
369         ret = 0;
370         is_delete = false;
371         is_return = false;
372         event = NULL;
373         group = NULL;
374
375         /* argc must be >= 1 */
376         if (argv[0][0] == '-')
377                 is_delete = true;
378         else if (argv[0][0] == 'r')
379                 is_return = true;
380         else if (argv[0][0] != 'p') {
381                 pr_info("Probe definition must be started with 'p', 'r' or '-'.\n");
382                 return -EINVAL;
383         }
384
385         if (argv[0][1] == ':') {
386                 event = &argv[0][2];
387                 arg = strchr(event, '/');
388
389                 if (arg) {
390                         group = event;
391                         event = arg + 1;
392                         event[-1] = '\0';
393
394                         if (strlen(group) == 0) {
395                                 pr_info("Group name is not specified\n");
396                                 return -EINVAL;
397                         }
398                 }
399                 if (strlen(event) == 0) {
400                         pr_info("Event name is not specified\n");
401                         return -EINVAL;
402                 }
403         }
404         if (!group)
405                 group = UPROBE_EVENT_SYSTEM;
406
407         if (is_delete) {
408                 int ret;
409
410                 if (!event) {
411                         pr_info("Delete command needs an event name.\n");
412                         return -EINVAL;
413                 }
414                 mutex_lock(&uprobe_lock);
415                 tu = find_probe_event(event, group);
416
417                 if (!tu) {
418                         mutex_unlock(&uprobe_lock);
419                         pr_info("Event %s/%s doesn't exist.\n", group, event);
420                         return -ENOENT;
421                 }
422                 /* delete an event */
423                 ret = unregister_trace_uprobe(tu);
424                 mutex_unlock(&uprobe_lock);
425                 return ret;
426         }
427
428         if (argc < 2) {
429                 pr_info("Probe point is not specified.\n");
430                 return -EINVAL;
431         }
432         /* Find the last occurrence, in case the path contains ':' too. */
433         arg = strrchr(argv[1], ':');
434         if (!arg)
435                 return -EINVAL;
436
437         *arg++ = '\0';
438         filename = argv[1];
439         ret = kern_path(filename, LOOKUP_FOLLOW, &path);
440         if (ret)
441                 return ret;
442
443         if (!d_is_reg(path.dentry)) {
444                 ret = -EINVAL;
445                 goto fail_address_parse;
446         }
447
448         ret = kstrtoul(arg, 0, &offset);
449         if (ret)
450                 goto fail_address_parse;
451
452         argc -= 2;
453         argv += 2;
454
455         /* setup a probe */
456         if (!event) {
457                 char *tail;
458                 char *ptr;
459
460                 tail = kstrdup(kbasename(filename), GFP_KERNEL);
461                 if (!tail) {
462                         ret = -ENOMEM;
463                         goto fail_address_parse;
464                 }
465
466                 ptr = strpbrk(tail, ".-_");
467                 if (ptr)
468                         *ptr = '\0';
469
470                 snprintf(buf, MAX_EVENT_NAME_LEN, "%c_%s_0x%lx", 'p', tail, offset);
471                 event = buf;
472                 kfree(tail);
473         }
474
475         tu = alloc_trace_uprobe(group, event, argc, is_return);
476         if (IS_ERR(tu)) {
477                 pr_info("Failed to allocate trace_uprobe.(%d)\n", (int)PTR_ERR(tu));
478                 ret = PTR_ERR(tu);
479                 goto fail_address_parse;
480         }
481         tu->offset = offset;
482         tu->path = path;
483         tu->filename = kstrdup(filename, GFP_KERNEL);
484
485         if (!tu->filename) {
486                 pr_info("Failed to allocate filename.\n");
487                 ret = -ENOMEM;
488                 goto error;
489         }
490
491         /* parse arguments */
492         ret = 0;
493         for (i = 0; i < argc && i < MAX_TRACE_ARGS; i++) {
494                 struct probe_arg *parg = &tu->tp.args[i];
495
496                 /* Increment count for freeing args in error case */
497                 tu->tp.nr_args++;
498
499                 /* Parse argument name */
500                 arg = strchr(argv[i], '=');
501                 if (arg) {
502                         *arg++ = '\0';
503                         parg->name = kstrdup(argv[i], GFP_KERNEL);
504                 } else {
505                         arg = argv[i];
506                         /* If argument name is omitted, set "argN" */
507                         snprintf(buf, MAX_EVENT_NAME_LEN, "arg%d", i + 1);
508                         parg->name = kstrdup(buf, GFP_KERNEL);
509                 }
510
511                 if (!parg->name) {
512                         pr_info("Failed to allocate argument[%d] name.\n", i);
513                         ret = -ENOMEM;
514                         goto error;
515                 }
516
517                 if (!is_good_name(parg->name)) {
518                         pr_info("Invalid argument[%d] name: %s\n", i, parg->name);
519                         ret = -EINVAL;
520                         goto error;
521                 }
522
523                 if (traceprobe_conflict_field_name(parg->name, tu->tp.args, i)) {
524                         pr_info("Argument[%d] name '%s' conflicts with "
525                                 "another field.\n", i, argv[i]);
526                         ret = -EINVAL;
527                         goto error;
528                 }
529
530                 /* Parse fetch argument */
531                 ret = traceprobe_parse_probe_arg(arg, &tu->tp.size, parg,
532                                                  is_return, false,
533                                                  uprobes_fetch_type_table);
534                 if (ret) {
535                         pr_info("Parse error at argument[%d]. (%d)\n", i, ret);
536                         goto error;
537                 }
538         }
539
540         ret = register_trace_uprobe(tu);
541         if (ret)
542                 goto error;
543         return 0;
544
545 error:
546         free_trace_uprobe(tu);
547         return ret;
548
549 fail_address_parse:
550         path_put(&path);
551
552         pr_info("Failed to parse address or file.\n");
553
554         return ret;
555 }
556
557 static int cleanup_all_probes(void)
558 {
559         struct trace_uprobe *tu;
560         int ret = 0;
561
562         mutex_lock(&uprobe_lock);
563         while (!list_empty(&uprobe_list)) {
564                 tu = list_entry(uprobe_list.next, struct trace_uprobe, list);
565                 ret = unregister_trace_uprobe(tu);
566                 if (ret)
567                         break;
568         }
569         mutex_unlock(&uprobe_lock);
570         return ret;
571 }
572
573 /* Probes listing interfaces */
574 static void *probes_seq_start(struct seq_file *m, loff_t *pos)
575 {
576         mutex_lock(&uprobe_lock);
577         return seq_list_start(&uprobe_list, *pos);
578 }
579
580 static void *probes_seq_next(struct seq_file *m, void *v, loff_t *pos)
581 {
582         return seq_list_next(v, &uprobe_list, pos);
583 }
584
585 static void probes_seq_stop(struct seq_file *m, void *v)
586 {
587         mutex_unlock(&uprobe_lock);
588 }
589
590 static int probes_seq_show(struct seq_file *m, void *v)
591 {
592         struct trace_uprobe *tu = v;
593         char c = is_ret_probe(tu) ? 'r' : 'p';
594         int i;
595
596         seq_printf(m, "%c:%s/%s %s:0x%0*lx", c, tu->tp.call.class->system,
597                         trace_event_name(&tu->tp.call), tu->filename,
598                         (int)(sizeof(void *) * 2), tu->offset);
599
600         for (i = 0; i < tu->tp.nr_args; i++)
601                 seq_printf(m, " %s=%s", tu->tp.args[i].name, tu->tp.args[i].comm);
602
603         seq_putc(m, '\n');
604         return 0;
605 }
606
607 static const struct seq_operations probes_seq_op = {
608         .start  = probes_seq_start,
609         .next   = probes_seq_next,
610         .stop   = probes_seq_stop,
611         .show   = probes_seq_show
612 };
613
614 static int probes_open(struct inode *inode, struct file *file)
615 {
616         int ret;
617
618         if ((file->f_mode & FMODE_WRITE) && (file->f_flags & O_TRUNC)) {
619                 ret = cleanup_all_probes();
620                 if (ret)
621                         return ret;
622         }
623
624         return seq_open(file, &probes_seq_op);
625 }
626
627 static ssize_t probes_write(struct file *file, const char __user *buffer,
628                             size_t count, loff_t *ppos)
629 {
630         return trace_parse_run_command(file, buffer, count, ppos, create_trace_uprobe);
631 }
632
633 static const struct file_operations uprobe_events_ops = {
634         .owner          = THIS_MODULE,
635         .open           = probes_open,
636         .read           = seq_read,
637         .llseek         = seq_lseek,
638         .release        = seq_release,
639         .write          = probes_write,
640 };
641
642 /* Probes profiling interfaces */
643 static int probes_profile_seq_show(struct seq_file *m, void *v)
644 {
645         struct trace_uprobe *tu = v;
646
647         seq_printf(m, "  %s %-44s %15lu\n", tu->filename,
648                         trace_event_name(&tu->tp.call), tu->nhit);
649         return 0;
650 }
651
652 static const struct seq_operations profile_seq_op = {
653         .start  = probes_seq_start,
654         .next   = probes_seq_next,
655         .stop   = probes_seq_stop,
656         .show   = probes_profile_seq_show
657 };
658
659 static int profile_open(struct inode *inode, struct file *file)
660 {
661         return seq_open(file, &profile_seq_op);
662 }
663
664 static const struct file_operations uprobe_profile_ops = {
665         .owner          = THIS_MODULE,
666         .open           = profile_open,
667         .read           = seq_read,
668         .llseek         = seq_lseek,
669         .release        = seq_release,
670 };
671
672 struct uprobe_cpu_buffer {
673         struct mutex mutex;
674         void *buf;
675 };
676 static struct uprobe_cpu_buffer __percpu *uprobe_cpu_buffer;
677 static int uprobe_buffer_refcnt;
678
679 static int uprobe_buffer_init(void)
680 {
681         int cpu, err_cpu;
682
683         uprobe_cpu_buffer = alloc_percpu(struct uprobe_cpu_buffer);
684         if (uprobe_cpu_buffer == NULL)
685                 return -ENOMEM;
686
687         for_each_possible_cpu(cpu) {
688                 struct page *p = alloc_pages_node(cpu_to_node(cpu),
689                                                   GFP_KERNEL, 0);
690                 if (p == NULL) {
691                         err_cpu = cpu;
692                         goto err;
693                 }
694                 per_cpu_ptr(uprobe_cpu_buffer, cpu)->buf = page_address(p);
695                 mutex_init(&per_cpu_ptr(uprobe_cpu_buffer, cpu)->mutex);
696         }
697
698         return 0;
699
700 err:
701         for_each_possible_cpu(cpu) {
702                 if (cpu == err_cpu)
703                         break;
704                 free_page((unsigned long)per_cpu_ptr(uprobe_cpu_buffer, cpu)->buf);
705         }
706
707         free_percpu(uprobe_cpu_buffer);
708         return -ENOMEM;
709 }
710
711 static int uprobe_buffer_enable(void)
712 {
713         int ret = 0;
714
715         BUG_ON(!mutex_is_locked(&event_mutex));
716
717         if (uprobe_buffer_refcnt++ == 0) {
718                 ret = uprobe_buffer_init();
719                 if (ret < 0)
720                         uprobe_buffer_refcnt--;
721         }
722
723         return ret;
724 }
725
726 static void uprobe_buffer_disable(void)
727 {
728         int cpu;
729
730         BUG_ON(!mutex_is_locked(&event_mutex));
731
732         if (--uprobe_buffer_refcnt == 0) {
733                 for_each_possible_cpu(cpu)
734                         free_page((unsigned long)per_cpu_ptr(uprobe_cpu_buffer,
735                                                              cpu)->buf);
736
737                 free_percpu(uprobe_cpu_buffer);
738                 uprobe_cpu_buffer = NULL;
739         }
740 }
741
742 static struct uprobe_cpu_buffer *uprobe_buffer_get(void)
743 {
744         struct uprobe_cpu_buffer *ucb;
745         int cpu;
746
747         cpu = raw_smp_processor_id();
748         ucb = per_cpu_ptr(uprobe_cpu_buffer, cpu);
749
750         /*
751          * Use per-cpu buffers for fastest access, but we might migrate
752          * so the mutex makes sure we have sole access to it.
753          */
754         mutex_lock(&ucb->mutex);
755
756         return ucb;
757 }
758
759 static void uprobe_buffer_put(struct uprobe_cpu_buffer *ucb)
760 {
761         mutex_unlock(&ucb->mutex);
762 }
763
764 static void __uprobe_trace_func(struct trace_uprobe *tu,
765                                 unsigned long func, struct pt_regs *regs,
766                                 struct uprobe_cpu_buffer *ucb, int dsize,
767                                 struct trace_event_file *trace_file)
768 {
769         struct uprobe_trace_entry_head *entry;
770         struct ring_buffer_event *event;
771         struct ring_buffer *buffer;
772         void *data;
773         int size, esize;
774         struct trace_event_call *call = &tu->tp.call;
775
776         WARN_ON(call != trace_file->event_call);
777
778         if (WARN_ON_ONCE(tu->tp.size + dsize > PAGE_SIZE))
779                 return;
780
781         if (trace_trigger_soft_disabled(trace_file))
782                 return;
783
784         esize = SIZEOF_TRACE_ENTRY(is_ret_probe(tu));
785         size = esize + tu->tp.size + dsize;
786         event = trace_event_buffer_lock_reserve(&buffer, trace_file,
787                                                 call->event.type, size, 0, 0);
788         if (!event)
789                 return;
790
791         entry = ring_buffer_event_data(event);
792         if (is_ret_probe(tu)) {
793                 entry->vaddr[0] = func;
794                 entry->vaddr[1] = instruction_pointer(regs);
795                 data = DATAOF_TRACE_ENTRY(entry, true);
796         } else {
797                 entry->vaddr[0] = instruction_pointer(regs);
798                 data = DATAOF_TRACE_ENTRY(entry, false);
799         }
800
801         memcpy(data, ucb->buf, tu->tp.size + dsize);
802
803         event_trigger_unlock_commit(trace_file, buffer, event, entry, 0, 0);
804 }
805
806 /* uprobe handler */
807 static int uprobe_trace_func(struct trace_uprobe *tu, struct pt_regs *regs,
808                              struct uprobe_cpu_buffer *ucb, int dsize)
809 {
810         struct event_file_link *link;
811
812         if (is_ret_probe(tu))
813                 return 0;
814
815         rcu_read_lock();
816         list_for_each_entry_rcu(link, &tu->tp.files, list)
817                 __uprobe_trace_func(tu, 0, regs, ucb, dsize, link->file);
818         rcu_read_unlock();
819
820         return 0;
821 }
822
823 static void uretprobe_trace_func(struct trace_uprobe *tu, unsigned long func,
824                                  struct pt_regs *regs,
825                                  struct uprobe_cpu_buffer *ucb, int dsize)
826 {
827         struct event_file_link *link;
828
829         rcu_read_lock();
830         list_for_each_entry_rcu(link, &tu->tp.files, list)
831                 __uprobe_trace_func(tu, func, regs, ucb, dsize, link->file);
832         rcu_read_unlock();
833 }
834
835 /* Event entry printers */
836 static enum print_line_t
837 print_uprobe_event(struct trace_iterator *iter, int flags, struct trace_event *event)
838 {
839         struct uprobe_trace_entry_head *entry;
840         struct trace_seq *s = &iter->seq;
841         struct trace_uprobe *tu;
842         u8 *data;
843         int i;
844
845         entry = (struct uprobe_trace_entry_head *)iter->ent;
846         tu = container_of(event, struct trace_uprobe, tp.call.event);
847
848         if (is_ret_probe(tu)) {
849                 trace_seq_printf(s, "%s: (0x%lx <- 0x%lx)",
850                                  trace_event_name(&tu->tp.call),
851                                  entry->vaddr[1], entry->vaddr[0]);
852                 data = DATAOF_TRACE_ENTRY(entry, true);
853         } else {
854                 trace_seq_printf(s, "%s: (0x%lx)",
855                                  trace_event_name(&tu->tp.call),
856                                  entry->vaddr[0]);
857                 data = DATAOF_TRACE_ENTRY(entry, false);
858         }
859
860         for (i = 0; i < tu->tp.nr_args; i++) {
861                 struct probe_arg *parg = &tu->tp.args[i];
862
863                 if (!parg->type->print(s, parg->name, data + parg->offset, entry))
864                         goto out;
865         }
866
867         trace_seq_putc(s, '\n');
868
869  out:
870         return trace_handle_return(s);
871 }
872
873 typedef bool (*filter_func_t)(struct uprobe_consumer *self,
874                                 enum uprobe_filter_ctx ctx,
875                                 struct mm_struct *mm);
876
877 static int
878 probe_event_enable(struct trace_uprobe *tu, struct trace_event_file *file,
879                    filter_func_t filter)
880 {
881         bool enabled = trace_probe_is_enabled(&tu->tp);
882         struct event_file_link *link = NULL;
883         int ret;
884
885         if (file) {
886                 if (tu->tp.flags & TP_FLAG_PROFILE)
887                         return -EINTR;
888
889                 link = kmalloc(sizeof(*link), GFP_KERNEL);
890                 if (!link)
891                         return -ENOMEM;
892
893                 link->file = file;
894                 list_add_tail_rcu(&link->list, &tu->tp.files);
895
896                 tu->tp.flags |= TP_FLAG_TRACE;
897         } else {
898                 if (tu->tp.flags & TP_FLAG_TRACE)
899                         return -EINTR;
900
901                 tu->tp.flags |= TP_FLAG_PROFILE;
902         }
903
904         WARN_ON(!uprobe_filter_is_empty(&tu->filter));
905
906         if (enabled)
907                 return 0;
908
909         ret = uprobe_buffer_enable();
910         if (ret)
911                 goto err_flags;
912
913         tu->consumer.filter = filter;
914         tu->inode = d_real_inode(tu->path.dentry);
915         ret = uprobe_register(tu->inode, tu->offset, &tu->consumer);
916         if (ret)
917                 goto err_buffer;
918
919         return 0;
920
921  err_buffer:
922         uprobe_buffer_disable();
923
924  err_flags:
925         if (file) {
926                 list_del(&link->list);
927                 kfree(link);
928                 tu->tp.flags &= ~TP_FLAG_TRACE;
929         } else {
930                 tu->tp.flags &= ~TP_FLAG_PROFILE;
931         }
932         return ret;
933 }
934
935 static void
936 probe_event_disable(struct trace_uprobe *tu, struct trace_event_file *file)
937 {
938         if (!trace_probe_is_enabled(&tu->tp))
939                 return;
940
941         if (file) {
942                 struct event_file_link *link;
943
944                 link = find_event_file_link(&tu->tp, file);
945                 if (!link)
946                         return;
947
948                 list_del_rcu(&link->list);
949                 /* synchronize with u{,ret}probe_trace_func */
950                 synchronize_rcu();
951                 kfree(link);
952
953                 if (!list_empty(&tu->tp.files))
954                         return;
955         }
956
957         WARN_ON(!uprobe_filter_is_empty(&tu->filter));
958
959         uprobe_unregister(tu->inode, tu->offset, &tu->consumer);
960         tu->inode = NULL;
961         tu->tp.flags &= file ? ~TP_FLAG_TRACE : ~TP_FLAG_PROFILE;
962
963         uprobe_buffer_disable();
964 }
965
966 static int uprobe_event_define_fields(struct trace_event_call *event_call)
967 {
968         int ret, i, size;
969         struct uprobe_trace_entry_head field;
970         struct trace_uprobe *tu = event_call->data;
971
972         if (is_ret_probe(tu)) {
973                 DEFINE_FIELD(unsigned long, vaddr[0], FIELD_STRING_FUNC, 0);
974                 DEFINE_FIELD(unsigned long, vaddr[1], FIELD_STRING_RETIP, 0);
975                 size = SIZEOF_TRACE_ENTRY(true);
976         } else {
977                 DEFINE_FIELD(unsigned long, vaddr[0], FIELD_STRING_IP, 0);
978                 size = SIZEOF_TRACE_ENTRY(false);
979         }
980         /* Set argument names as fields */
981         for (i = 0; i < tu->tp.nr_args; i++) {
982                 struct probe_arg *parg = &tu->tp.args[i];
983
984                 ret = trace_define_field(event_call, parg->type->fmttype,
985                                          parg->name, size + parg->offset,
986                                          parg->type->size, parg->type->is_signed,
987                                          FILTER_OTHER);
988
989                 if (ret)
990                         return ret;
991         }
992         return 0;
993 }
994
995 #ifdef CONFIG_PERF_EVENTS
996 static bool
997 __uprobe_perf_filter(struct trace_uprobe_filter *filter, struct mm_struct *mm)
998 {
999         struct perf_event *event;
1000
1001         if (filter->nr_systemwide)
1002                 return true;
1003
1004         list_for_each_entry(event, &filter->perf_events, hw.tp_list) {
1005                 if (event->hw.target->mm == mm)
1006                         return true;
1007         }
1008
1009         return false;
1010 }
1011
1012 static inline bool
1013 uprobe_filter_event(struct trace_uprobe *tu, struct perf_event *event)
1014 {
1015         return __uprobe_perf_filter(&tu->filter, event->hw.target->mm);
1016 }
1017
1018 static int uprobe_perf_close(struct trace_uprobe *tu, struct perf_event *event)
1019 {
1020         bool done;
1021
1022         write_lock(&tu->filter.rwlock);
1023         if (event->hw.target) {
1024                 list_del(&event->hw.tp_list);
1025                 done = tu->filter.nr_systemwide ||
1026                         (event->hw.target->flags & PF_EXITING) ||
1027                         uprobe_filter_event(tu, event);
1028         } else {
1029                 tu->filter.nr_systemwide--;
1030                 done = tu->filter.nr_systemwide;
1031         }
1032         write_unlock(&tu->filter.rwlock);
1033
1034         if (!done)
1035                 return uprobe_apply(tu->inode, tu->offset, &tu->consumer, false);
1036
1037         return 0;
1038 }
1039
1040 static int uprobe_perf_open(struct trace_uprobe *tu, struct perf_event *event)
1041 {
1042         bool done;
1043         int err;
1044
1045         write_lock(&tu->filter.rwlock);
1046         if (event->hw.target) {
1047                 /*
1048                  * event->parent != NULL means copy_process(), we can avoid
1049                  * uprobe_apply(). current->mm must be probed and we can rely
1050                  * on dup_mmap() which preserves the already installed bp's.
1051                  *
1052                  * attr.enable_on_exec means that exec/mmap will install the
1053                  * breakpoints we need.
1054                  */
1055                 done = tu->filter.nr_systemwide ||
1056                         event->parent || event->attr.enable_on_exec ||
1057                         uprobe_filter_event(tu, event);
1058                 list_add(&event->hw.tp_list, &tu->filter.perf_events);
1059         } else {
1060                 done = tu->filter.nr_systemwide;
1061                 tu->filter.nr_systemwide++;
1062         }
1063         write_unlock(&tu->filter.rwlock);
1064
1065         err = 0;
1066         if (!done) {
1067                 err = uprobe_apply(tu->inode, tu->offset, &tu->consumer, true);
1068                 if (err)
1069                         uprobe_perf_close(tu, event);
1070         }
1071         return err;
1072 }
1073
1074 static bool uprobe_perf_filter(struct uprobe_consumer *uc,
1075                                 enum uprobe_filter_ctx ctx, struct mm_struct *mm)
1076 {
1077         struct trace_uprobe *tu;
1078         int ret;
1079
1080         tu = container_of(uc, struct trace_uprobe, consumer);
1081         read_lock(&tu->filter.rwlock);
1082         ret = __uprobe_perf_filter(&tu->filter, mm);
1083         read_unlock(&tu->filter.rwlock);
1084
1085         return ret;
1086 }
1087
1088 static void __uprobe_perf_func(struct trace_uprobe *tu,
1089                                unsigned long func, struct pt_regs *regs,
1090                                struct uprobe_cpu_buffer *ucb, int dsize)
1091 {
1092         struct trace_event_call *call = &tu->tp.call;
1093         struct uprobe_trace_entry_head *entry;
1094         struct hlist_head *head;
1095         void *data;
1096         int size, esize;
1097         int rctx;
1098
1099         if (bpf_prog_array_valid(call) && !trace_call_bpf(call, regs))
1100                 return;
1101
1102         esize = SIZEOF_TRACE_ENTRY(is_ret_probe(tu));
1103
1104         size = esize + tu->tp.size + dsize;
1105         size = ALIGN(size + sizeof(u32), sizeof(u64)) - sizeof(u32);
1106         if (WARN_ONCE(size > PERF_MAX_TRACE_SIZE, "profile buffer not large enough"))
1107                 return;
1108
1109         preempt_disable();
1110         head = this_cpu_ptr(call->perf_events);
1111         if (hlist_empty(head))
1112                 goto out;
1113
1114         entry = perf_trace_buf_alloc(size, NULL, &rctx);
1115         if (!entry)
1116                 goto out;
1117
1118         if (is_ret_probe(tu)) {
1119                 entry->vaddr[0] = func;
1120                 entry->vaddr[1] = instruction_pointer(regs);
1121                 data = DATAOF_TRACE_ENTRY(entry, true);
1122         } else {
1123                 entry->vaddr[0] = instruction_pointer(regs);
1124                 data = DATAOF_TRACE_ENTRY(entry, false);
1125         }
1126
1127         memcpy(data, ucb->buf, tu->tp.size + dsize);
1128
1129         if (size - esize > tu->tp.size + dsize) {
1130                 int len = tu->tp.size + dsize;
1131
1132                 memset(data + len, 0, size - esize - len);
1133         }
1134
1135         perf_trace_buf_submit(entry, size, rctx, call->event.type, 1, regs,
1136                               head, NULL);
1137  out:
1138         preempt_enable();
1139 }
1140
1141 /* uprobe profile handler */
1142 static int uprobe_perf_func(struct trace_uprobe *tu, struct pt_regs *regs,
1143                             struct uprobe_cpu_buffer *ucb, int dsize)
1144 {
1145         if (!uprobe_perf_filter(&tu->consumer, 0, current->mm))
1146                 return UPROBE_HANDLER_REMOVE;
1147
1148         if (!is_ret_probe(tu))
1149                 __uprobe_perf_func(tu, 0, regs, ucb, dsize);
1150         return 0;
1151 }
1152
1153 static void uretprobe_perf_func(struct trace_uprobe *tu, unsigned long func,
1154                                 struct pt_regs *regs,
1155                                 struct uprobe_cpu_buffer *ucb, int dsize)
1156 {
1157         __uprobe_perf_func(tu, func, regs, ucb, dsize);
1158 }
1159
1160 int bpf_get_uprobe_info(const struct perf_event *event, u32 *fd_type,
1161                         const char **filename, u64 *probe_offset,
1162                         bool perf_type_tracepoint)
1163 {
1164         const char *pevent = trace_event_name(event->tp_event);
1165         const char *group = event->tp_event->class->system;
1166         struct trace_uprobe *tu;
1167
1168         if (perf_type_tracepoint)
1169                 tu = find_probe_event(pevent, group);
1170         else
1171                 tu = event->tp_event->data;
1172         if (!tu)
1173                 return -EINVAL;
1174
1175         *fd_type = is_ret_probe(tu) ? BPF_FD_TYPE_URETPROBE
1176                                     : BPF_FD_TYPE_UPROBE;
1177         *filename = tu->filename;
1178         *probe_offset = tu->offset;
1179         return 0;
1180 }
1181 #endif  /* CONFIG_PERF_EVENTS */
1182
1183 static int
1184 trace_uprobe_register(struct trace_event_call *event, enum trace_reg type,
1185                       void *data)
1186 {
1187         struct trace_uprobe *tu = event->data;
1188         struct trace_event_file *file = data;
1189
1190         switch (type) {
1191         case TRACE_REG_REGISTER:
1192                 return probe_event_enable(tu, file, NULL);
1193
1194         case TRACE_REG_UNREGISTER:
1195                 probe_event_disable(tu, file);
1196                 return 0;
1197
1198 #ifdef CONFIG_PERF_EVENTS
1199         case TRACE_REG_PERF_REGISTER:
1200                 return probe_event_enable(tu, NULL, uprobe_perf_filter);
1201
1202         case TRACE_REG_PERF_UNREGISTER:
1203                 probe_event_disable(tu, NULL);
1204                 return 0;
1205
1206         case TRACE_REG_PERF_OPEN:
1207                 return uprobe_perf_open(tu, data);
1208
1209         case TRACE_REG_PERF_CLOSE:
1210                 return uprobe_perf_close(tu, data);
1211
1212 #endif
1213         default:
1214                 return 0;
1215         }
1216         return 0;
1217 }
1218
1219 static int uprobe_dispatcher(struct uprobe_consumer *con, struct pt_regs *regs)
1220 {
1221         struct trace_uprobe *tu;
1222         struct uprobe_dispatch_data udd;
1223         struct uprobe_cpu_buffer *ucb;
1224         int dsize, esize;
1225         int ret = 0;
1226
1227
1228         tu = container_of(con, struct trace_uprobe, consumer);
1229         tu->nhit++;
1230
1231         udd.tu = tu;
1232         udd.bp_addr = instruction_pointer(regs);
1233
1234         current->utask->vaddr = (unsigned long) &udd;
1235
1236         if (WARN_ON_ONCE(!uprobe_cpu_buffer))
1237                 return 0;
1238
1239         dsize = __get_data_size(&tu->tp, regs);
1240         esize = SIZEOF_TRACE_ENTRY(is_ret_probe(tu));
1241
1242         ucb = uprobe_buffer_get();
1243         store_trace_args(esize, &tu->tp, regs, ucb->buf, dsize);
1244
1245         if (tu->tp.flags & TP_FLAG_TRACE)
1246                 ret |= uprobe_trace_func(tu, regs, ucb, dsize);
1247
1248 #ifdef CONFIG_PERF_EVENTS
1249         if (tu->tp.flags & TP_FLAG_PROFILE)
1250                 ret |= uprobe_perf_func(tu, regs, ucb, dsize);
1251 #endif
1252         uprobe_buffer_put(ucb);
1253         return ret;
1254 }
1255
1256 static int uretprobe_dispatcher(struct uprobe_consumer *con,
1257                                 unsigned long func, struct pt_regs *regs)
1258 {
1259         struct trace_uprobe *tu;
1260         struct uprobe_dispatch_data udd;
1261         struct uprobe_cpu_buffer *ucb;
1262         int dsize, esize;
1263
1264         tu = container_of(con, struct trace_uprobe, consumer);
1265
1266         udd.tu = tu;
1267         udd.bp_addr = func;
1268
1269         current->utask->vaddr = (unsigned long) &udd;
1270
1271         if (WARN_ON_ONCE(!uprobe_cpu_buffer))
1272                 return 0;
1273
1274         dsize = __get_data_size(&tu->tp, regs);
1275         esize = SIZEOF_TRACE_ENTRY(is_ret_probe(tu));
1276
1277         ucb = uprobe_buffer_get();
1278         store_trace_args(esize, &tu->tp, regs, ucb->buf, dsize);
1279
1280         if (tu->tp.flags & TP_FLAG_TRACE)
1281                 uretprobe_trace_func(tu, func, regs, ucb, dsize);
1282
1283 #ifdef CONFIG_PERF_EVENTS
1284         if (tu->tp.flags & TP_FLAG_PROFILE)
1285                 uretprobe_perf_func(tu, func, regs, ucb, dsize);
1286 #endif
1287         uprobe_buffer_put(ucb);
1288         return 0;
1289 }
1290
1291 static struct trace_event_functions uprobe_funcs = {
1292         .trace          = print_uprobe_event
1293 };
1294
1295 static inline void init_trace_event_call(struct trace_uprobe *tu,
1296                                          struct trace_event_call *call)
1297 {
1298         INIT_LIST_HEAD(&call->class->fields);
1299         call->event.funcs = &uprobe_funcs;
1300         call->class->define_fields = uprobe_event_define_fields;
1301
1302         call->flags = TRACE_EVENT_FL_UPROBE;
1303         call->class->reg = trace_uprobe_register;
1304         call->data = tu;
1305 }
1306
1307 static int register_uprobe_event(struct trace_uprobe *tu)
1308 {
1309         struct trace_event_call *call = &tu->tp.call;
1310         int ret = 0;
1311
1312         init_trace_event_call(tu, call);
1313
1314         if (set_print_fmt(&tu->tp, is_ret_probe(tu)) < 0)
1315                 return -ENOMEM;
1316
1317         ret = register_trace_event(&call->event);
1318         if (!ret) {
1319                 kfree(call->print_fmt);
1320                 return -ENODEV;
1321         }
1322
1323         ret = trace_add_event_call(call);
1324
1325         if (ret) {
1326                 pr_info("Failed to register uprobe event: %s\n",
1327                         trace_event_name(call));
1328                 kfree(call->print_fmt);
1329                 unregister_trace_event(&call->event);
1330         }
1331
1332         return ret;
1333 }
1334
1335 static int unregister_uprobe_event(struct trace_uprobe *tu)
1336 {
1337         int ret;
1338
1339         /* tu->event is unregistered in trace_remove_event_call() */
1340         ret = trace_remove_event_call(&tu->tp.call);
1341         if (ret)
1342                 return ret;
1343         kfree(tu->tp.call.print_fmt);
1344         tu->tp.call.print_fmt = NULL;
1345         return 0;
1346 }
1347
1348 #ifdef CONFIG_PERF_EVENTS
1349 struct trace_event_call *
1350 create_local_trace_uprobe(char *name, unsigned long offs, bool is_return)
1351 {
1352         struct trace_uprobe *tu;
1353         struct path path;
1354         int ret;
1355
1356         ret = kern_path(name, LOOKUP_FOLLOW, &path);
1357         if (ret)
1358                 return ERR_PTR(ret);
1359
1360         if (!d_is_reg(path.dentry)) {
1361                 path_put(&path);
1362                 return ERR_PTR(-EINVAL);
1363         }
1364
1365         /*
1366          * local trace_kprobes are not added to probe_list, so they are never
1367          * searched in find_trace_kprobe(). Therefore, there is no concern of
1368          * duplicated name "DUMMY_EVENT" here.
1369          */
1370         tu = alloc_trace_uprobe(UPROBE_EVENT_SYSTEM, "DUMMY_EVENT", 0,
1371                                 is_return);
1372
1373         if (IS_ERR(tu)) {
1374                 pr_info("Failed to allocate trace_uprobe.(%d)\n",
1375                         (int)PTR_ERR(tu));
1376                 path_put(&path);
1377                 return ERR_CAST(tu);
1378         }
1379
1380         tu->offset = offs;
1381         tu->path = path;
1382         tu->filename = kstrdup(name, GFP_KERNEL);
1383         init_trace_event_call(tu, &tu->tp.call);
1384
1385         if (set_print_fmt(&tu->tp, is_ret_probe(tu)) < 0) {
1386                 ret = -ENOMEM;
1387                 goto error;
1388         }
1389
1390         return &tu->tp.call;
1391 error:
1392         free_trace_uprobe(tu);
1393         return ERR_PTR(ret);
1394 }
1395
1396 void destroy_local_trace_uprobe(struct trace_event_call *event_call)
1397 {
1398         struct trace_uprobe *tu;
1399
1400         tu = container_of(event_call, struct trace_uprobe, tp.call);
1401
1402         kfree(tu->tp.call.print_fmt);
1403         tu->tp.call.print_fmt = NULL;
1404
1405         free_trace_uprobe(tu);
1406 }
1407 #endif /* CONFIG_PERF_EVENTS */
1408
1409 /* Make a trace interface for controling probe points */
1410 static __init int init_uprobe_trace(void)
1411 {
1412         struct dentry *d_tracer;
1413
1414         d_tracer = tracing_init_dentry();
1415         if (IS_ERR(d_tracer))
1416                 return 0;
1417
1418         trace_create_file("uprobe_events", 0644, d_tracer,
1419                                     NULL, &uprobe_events_ops);
1420         /* Profile interface */
1421         trace_create_file("uprobe_profile", 0444, d_tracer,
1422                                     NULL, &uprobe_profile_ops);
1423         return 0;
1424 }
1425
1426 fs_initcall(init_uprobe_trace);