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