2088893c049efc03dd0ece7486bf34fd5959914c
[firefly-linux-kernel-4.4.55.git] / kernel / trace / trace_kprobe.c
1 /*
2  * Kprobes-based tracing events
3  *
4  * Created by Masami Hiramatsu <mhiramat@redhat.com>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 #include <linux/module.h>
21 #include <linux/uaccess.h>
22 #include <linux/kprobes.h>
23 #include <linux/seq_file.h>
24 #include <linux/slab.h>
25 #include <linux/smp.h>
26 #include <linux/debugfs.h>
27 #include <linux/types.h>
28 #include <linux/string.h>
29 #include <linux/ctype.h>
30 #include <linux/ptrace.h>
31 #include <linux/perf_event.h>
32 #include <linux/stringify.h>
33 #include <linux/limits.h>
34 #include <asm/bitsperlong.h>
35
36 #include "trace.h"
37 #include "trace_output.h"
38
39 #define MAX_TRACE_ARGS 128
40 #define MAX_ARGSTR_LEN 63
41 #define MAX_EVENT_NAME_LEN 64
42 #define MAX_STRING_SIZE PATH_MAX
43 #define KPROBE_EVENT_SYSTEM "kprobes"
44
45 /* Reserved field names */
46 #define FIELD_STRING_IP "__probe_ip"
47 #define FIELD_STRING_RETIP "__probe_ret_ip"
48 #define FIELD_STRING_FUNC "__probe_func"
49
50 const char *reserved_field_names[] = {
51         "common_type",
52         "common_flags",
53         "common_preempt_count",
54         "common_pid",
55         "common_tgid",
56         "common_lock_depth",
57         FIELD_STRING_IP,
58         FIELD_STRING_RETIP,
59         FIELD_STRING_FUNC,
60 };
61
62 /* Printing function type */
63 typedef int (*print_type_func_t)(struct trace_seq *, const char *, void *,
64                                  void *);
65 #define PRINT_TYPE_FUNC_NAME(type)      print_type_##type
66 #define PRINT_TYPE_FMT_NAME(type)       print_type_format_##type
67
68 /* Printing  in basic type function template */
69 #define DEFINE_BASIC_PRINT_TYPE_FUNC(type, fmt, cast)                   \
70 static __kprobes int PRINT_TYPE_FUNC_NAME(type)(struct trace_seq *s,    \
71                                                 const char *name,       \
72                                                 void *data, void *ent)\
73 {                                                                       \
74         return trace_seq_printf(s, " %s=" fmt, name, (cast)*(type *)data);\
75 }                                                                       \
76 static const char PRINT_TYPE_FMT_NAME(type)[] = fmt;
77
78 DEFINE_BASIC_PRINT_TYPE_FUNC(u8, "%x", unsigned int)
79 DEFINE_BASIC_PRINT_TYPE_FUNC(u16, "%x", unsigned int)
80 DEFINE_BASIC_PRINT_TYPE_FUNC(u32, "%lx", unsigned long)
81 DEFINE_BASIC_PRINT_TYPE_FUNC(u64, "%llx", unsigned long long)
82 DEFINE_BASIC_PRINT_TYPE_FUNC(s8, "%d", int)
83 DEFINE_BASIC_PRINT_TYPE_FUNC(s16, "%d", int)
84 DEFINE_BASIC_PRINT_TYPE_FUNC(s32, "%ld", long)
85 DEFINE_BASIC_PRINT_TYPE_FUNC(s64, "%lld", long long)
86
87 /* data_rloc: data relative location, compatible with u32 */
88 #define make_data_rloc(len, roffs)      \
89         (((u32)(len) << 16) | ((u32)(roffs) & 0xffff))
90 #define get_rloc_len(dl)        ((u32)(dl) >> 16)
91 #define get_rloc_offs(dl)       ((u32)(dl) & 0xffff)
92
93 static inline void *get_rloc_data(u32 *dl)
94 {
95         return (u8 *)dl + get_rloc_offs(*dl);
96 }
97
98 /* For data_loc conversion */
99 static inline void *get_loc_data(u32 *dl, void *ent)
100 {
101         return (u8 *)ent + get_rloc_offs(*dl);
102 }
103
104 /*
105  * Convert data_rloc to data_loc:
106  *  data_rloc stores the offset from data_rloc itself, but data_loc
107  *  stores the offset from event entry.
108  */
109 #define convert_rloc_to_loc(dl, offs)   ((u32)(dl) + (offs))
110
111 /* For defining macros, define string/string_size types */
112 typedef u32 string;
113 typedef u32 string_size;
114
115 /* Print type function for string type */
116 static __kprobes int PRINT_TYPE_FUNC_NAME(string)(struct trace_seq *s,
117                                                   const char *name,
118                                                   void *data, void *ent)
119 {
120         int len = *(u32 *)data >> 16;
121
122         if (!len)
123                 return trace_seq_printf(s, " %s=(fault)", name);
124         else
125                 return trace_seq_printf(s, " %s=\"%s\"", name,
126                                         (const char *)get_loc_data(data, ent));
127 }
128 static const char PRINT_TYPE_FMT_NAME(string)[] = "\\\"%s\\\"";
129
130 /* Data fetch function type */
131 typedef void (*fetch_func_t)(struct pt_regs *, void *, void *);
132
133 struct fetch_param {
134         fetch_func_t    fn;
135         void *data;
136 };
137
138 static __kprobes void call_fetch(struct fetch_param *fprm,
139                                  struct pt_regs *regs, void *dest)
140 {
141         return fprm->fn(regs, fprm->data, dest);
142 }
143
144 #define FETCH_FUNC_NAME(method, type)   fetch_##method##_##type
145 /*
146  * Define macro for basic types - we don't need to define s* types, because
147  * we have to care only about bitwidth at recording time.
148  */
149 #define DEFINE_BASIC_FETCH_FUNCS(method) \
150 DEFINE_FETCH_##method(u8)               \
151 DEFINE_FETCH_##method(u16)              \
152 DEFINE_FETCH_##method(u32)              \
153 DEFINE_FETCH_##method(u64)
154
155 #define CHECK_FETCH_FUNCS(method, fn)                   \
156         (((FETCH_FUNC_NAME(method, u8) == fn) ||        \
157           (FETCH_FUNC_NAME(method, u16) == fn) ||       \
158           (FETCH_FUNC_NAME(method, u32) == fn) ||       \
159           (FETCH_FUNC_NAME(method, u64) == fn) ||       \
160           (FETCH_FUNC_NAME(method, string) == fn) ||    \
161           (FETCH_FUNC_NAME(method, string_size) == fn)) \
162          && (fn != NULL))
163
164 /* Data fetch function templates */
165 #define DEFINE_FETCH_reg(type)                                          \
166 static __kprobes void FETCH_FUNC_NAME(reg, type)(struct pt_regs *regs,  \
167                                         void *offset, void *dest)       \
168 {                                                                       \
169         *(type *)dest = (type)regs_get_register(regs,                   \
170                                 (unsigned int)((unsigned long)offset)); \
171 }
172 DEFINE_BASIC_FETCH_FUNCS(reg)
173 /* No string on the register */
174 #define fetch_reg_string NULL
175 #define fetch_reg_string_size NULL
176
177 #define DEFINE_FETCH_stack(type)                                        \
178 static __kprobes void FETCH_FUNC_NAME(stack, type)(struct pt_regs *regs,\
179                                           void *offset, void *dest)     \
180 {                                                                       \
181         *(type *)dest = (type)regs_get_kernel_stack_nth(regs,           \
182                                 (unsigned int)((unsigned long)offset)); \
183 }
184 DEFINE_BASIC_FETCH_FUNCS(stack)
185 /* No string on the stack entry */
186 #define fetch_stack_string NULL
187 #define fetch_stack_string_size NULL
188
189 #define DEFINE_FETCH_retval(type)                                       \
190 static __kprobes void FETCH_FUNC_NAME(retval, type)(struct pt_regs *regs,\
191                                           void *dummy, void *dest)      \
192 {                                                                       \
193         *(type *)dest = (type)regs_return_value(regs);                  \
194 }
195 DEFINE_BASIC_FETCH_FUNCS(retval)
196 /* No string on the retval */
197 #define fetch_retval_string NULL
198 #define fetch_retval_string_size NULL
199
200 #define DEFINE_FETCH_memory(type)                                       \
201 static __kprobes void FETCH_FUNC_NAME(memory, type)(struct pt_regs *regs,\
202                                           void *addr, void *dest)       \
203 {                                                                       \
204         type retval;                                                    \
205         if (probe_kernel_address(addr, retval))                         \
206                 *(type *)dest = 0;                                      \
207         else                                                            \
208                 *(type *)dest = retval;                                 \
209 }
210 DEFINE_BASIC_FETCH_FUNCS(memory)
211 /*
212  * Fetch a null-terminated string. Caller MUST set *(u32 *)dest with max
213  * length and relative data location.
214  */
215 static __kprobes void FETCH_FUNC_NAME(memory, string)(struct pt_regs *regs,
216                                                       void *addr, void *dest)
217 {
218         long ret;
219         int maxlen = get_rloc_len(*(u32 *)dest);
220         u8 *dst = get_rloc_data(dest);
221         u8 *src = addr;
222         mm_segment_t old_fs = get_fs();
223         if (!maxlen)
224                 return;
225         /*
226          * Try to get string again, since the string can be changed while
227          * probing.
228          */
229         set_fs(KERNEL_DS);
230         pagefault_disable();
231         do
232                 ret = __copy_from_user_inatomic(dst++, src++, 1);
233         while (dst[-1] && ret == 0 && src - (u8 *)addr < maxlen);
234         dst[-1] = '\0';
235         pagefault_enable();
236         set_fs(old_fs);
237
238         if (ret < 0) {  /* Failed to fetch string */
239                 ((u8 *)get_rloc_data(dest))[0] = '\0';
240                 *(u32 *)dest = make_data_rloc(0, get_rloc_offs(*(u32 *)dest));
241         } else
242                 *(u32 *)dest = make_data_rloc(src - (u8 *)addr,
243                                               get_rloc_offs(*(u32 *)dest));
244 }
245 /* Return the length of string -- including null terminal byte */
246 static __kprobes void FETCH_FUNC_NAME(memory, string_size)(struct pt_regs *regs,
247                                                         void *addr, void *dest)
248 {
249         int ret, len = 0;
250         u8 c;
251         mm_segment_t old_fs = get_fs();
252
253         set_fs(KERNEL_DS);
254         pagefault_disable();
255         do {
256                 ret = __copy_from_user_inatomic(&c, (u8 *)addr + len, 1);
257                 len++;
258         } while (c && ret == 0 && len < MAX_STRING_SIZE);
259         pagefault_enable();
260         set_fs(old_fs);
261
262         if (ret < 0)    /* Failed to check the length */
263                 *(u32 *)dest = 0;
264         else
265                 *(u32 *)dest = len;
266 }
267
268 /* Memory fetching by symbol */
269 struct symbol_cache {
270         char *symbol;
271         long offset;
272         unsigned long addr;
273 };
274
275 static unsigned long update_symbol_cache(struct symbol_cache *sc)
276 {
277         sc->addr = (unsigned long)kallsyms_lookup_name(sc->symbol);
278         if (sc->addr)
279                 sc->addr += sc->offset;
280         return sc->addr;
281 }
282
283 static void free_symbol_cache(struct symbol_cache *sc)
284 {
285         kfree(sc->symbol);
286         kfree(sc);
287 }
288
289 static struct symbol_cache *alloc_symbol_cache(const char *sym, long offset)
290 {
291         struct symbol_cache *sc;
292
293         if (!sym || strlen(sym) == 0)
294                 return NULL;
295         sc = kzalloc(sizeof(struct symbol_cache), GFP_KERNEL);
296         if (!sc)
297                 return NULL;
298
299         sc->symbol = kstrdup(sym, GFP_KERNEL);
300         if (!sc->symbol) {
301                 kfree(sc);
302                 return NULL;
303         }
304         sc->offset = offset;
305
306         update_symbol_cache(sc);
307         return sc;
308 }
309
310 #define DEFINE_FETCH_symbol(type)                                       \
311 static __kprobes void FETCH_FUNC_NAME(symbol, type)(struct pt_regs *regs,\
312                                           void *data, void *dest)       \
313 {                                                                       \
314         struct symbol_cache *sc = data;                                 \
315         if (sc->addr)                                                   \
316                 fetch_memory_##type(regs, (void *)sc->addr, dest);      \
317         else                                                            \
318                 *(type *)dest = 0;                                      \
319 }
320 DEFINE_BASIC_FETCH_FUNCS(symbol)
321 DEFINE_FETCH_symbol(string)
322 DEFINE_FETCH_symbol(string_size)
323
324 /* Dereference memory access function */
325 struct deref_fetch_param {
326         struct fetch_param orig;
327         long offset;
328 };
329
330 #define DEFINE_FETCH_deref(type)                                        \
331 static __kprobes void FETCH_FUNC_NAME(deref, type)(struct pt_regs *regs,\
332                                             void *data, void *dest)     \
333 {                                                                       \
334         struct deref_fetch_param *dprm = data;                          \
335         unsigned long addr;                                             \
336         call_fetch(&dprm->orig, regs, &addr);                           \
337         if (addr) {                                                     \
338                 addr += dprm->offset;                                   \
339                 fetch_memory_##type(regs, (void *)addr, dest);          \
340         } else                                                          \
341                 *(type *)dest = 0;                                      \
342 }
343 DEFINE_BASIC_FETCH_FUNCS(deref)
344 DEFINE_FETCH_deref(string)
345 DEFINE_FETCH_deref(string_size)
346
347 static __kprobes void free_deref_fetch_param(struct deref_fetch_param *data)
348 {
349         if (CHECK_FETCH_FUNCS(deref, data->orig.fn))
350                 free_deref_fetch_param(data->orig.data);
351         else if (CHECK_FETCH_FUNCS(symbol, data->orig.fn))
352                 free_symbol_cache(data->orig.data);
353         kfree(data);
354 }
355
356 /* Default (unsigned long) fetch type */
357 #define __DEFAULT_FETCH_TYPE(t) u##t
358 #define _DEFAULT_FETCH_TYPE(t) __DEFAULT_FETCH_TYPE(t)
359 #define DEFAULT_FETCH_TYPE _DEFAULT_FETCH_TYPE(BITS_PER_LONG)
360 #define DEFAULT_FETCH_TYPE_STR __stringify(DEFAULT_FETCH_TYPE)
361
362 /* Fetch types */
363 enum {
364         FETCH_MTD_reg = 0,
365         FETCH_MTD_stack,
366         FETCH_MTD_retval,
367         FETCH_MTD_memory,
368         FETCH_MTD_symbol,
369         FETCH_MTD_deref,
370         FETCH_MTD_END,
371 };
372
373 #define ASSIGN_FETCH_FUNC(method, type) \
374         [FETCH_MTD_##method] = FETCH_FUNC_NAME(method, type)
375
376 #define __ASSIGN_FETCH_TYPE(_name, ptype, ftype, _size, sign, _fmttype) \
377         {.name = _name,                         \
378          .size = _size,                                 \
379          .is_signed = sign,                             \
380          .print = PRINT_TYPE_FUNC_NAME(ptype),          \
381          .fmt = PRINT_TYPE_FMT_NAME(ptype),             \
382          .fmttype = _fmttype,                           \
383          .fetch = {                                     \
384 ASSIGN_FETCH_FUNC(reg, ftype),                          \
385 ASSIGN_FETCH_FUNC(stack, ftype),                        \
386 ASSIGN_FETCH_FUNC(retval, ftype),                       \
387 ASSIGN_FETCH_FUNC(memory, ftype),                       \
388 ASSIGN_FETCH_FUNC(symbol, ftype),                       \
389 ASSIGN_FETCH_FUNC(deref, ftype),                        \
390           }                                             \
391         }
392
393 #define ASSIGN_FETCH_TYPE(ptype, ftype, sign)                   \
394         __ASSIGN_FETCH_TYPE(#ptype, ptype, ftype, sizeof(ftype), sign, #ptype)
395
396 #define FETCH_TYPE_STRING 0
397 #define FETCH_TYPE_STRSIZE 1
398
399 /* Fetch type information table */
400 static const struct fetch_type {
401         const char      *name;          /* Name of type */
402         size_t          size;           /* Byte size of type */
403         int             is_signed;      /* Signed flag */
404         print_type_func_t       print;  /* Print functions */
405         const char      *fmt;           /* Fromat string */
406         const char      *fmttype;       /* Name in format file */
407         /* Fetch functions */
408         fetch_func_t    fetch[FETCH_MTD_END];
409 } fetch_type_table[] = {
410         /* Special types */
411         [FETCH_TYPE_STRING] = __ASSIGN_FETCH_TYPE("string", string, string,
412                                         sizeof(u32), 1, "__data_loc char[]"),
413         [FETCH_TYPE_STRSIZE] = __ASSIGN_FETCH_TYPE("string_size", u32,
414                                         string_size, sizeof(u32), 0, "u32"),
415         /* Basic types */
416         ASSIGN_FETCH_TYPE(u8,  u8,  0),
417         ASSIGN_FETCH_TYPE(u16, u16, 0),
418         ASSIGN_FETCH_TYPE(u32, u32, 0),
419         ASSIGN_FETCH_TYPE(u64, u64, 0),
420         ASSIGN_FETCH_TYPE(s8,  u8,  1),
421         ASSIGN_FETCH_TYPE(s16, u16, 1),
422         ASSIGN_FETCH_TYPE(s32, u32, 1),
423         ASSIGN_FETCH_TYPE(s64, u64, 1),
424 };
425
426 static const struct fetch_type *find_fetch_type(const char *type)
427 {
428         int i;
429
430         if (!type)
431                 type = DEFAULT_FETCH_TYPE_STR;
432
433         for (i = 0; i < ARRAY_SIZE(fetch_type_table); i++)
434                 if (strcmp(type, fetch_type_table[i].name) == 0)
435                         return &fetch_type_table[i];
436         return NULL;
437 }
438
439 /* Special function : only accept unsigned long */
440 static __kprobes void fetch_stack_address(struct pt_regs *regs,
441                                           void *dummy, void *dest)
442 {
443         *(unsigned long *)dest = kernel_stack_pointer(regs);
444 }
445
446 static fetch_func_t get_fetch_size_function(const struct fetch_type *type,
447                                             fetch_func_t orig_fn)
448 {
449         int i;
450
451         if (type != &fetch_type_table[FETCH_TYPE_STRING])
452                 return NULL;    /* Only string type needs size function */
453         for (i = 0; i < FETCH_MTD_END; i++)
454                 if (type->fetch[i] == orig_fn)
455                         return fetch_type_table[FETCH_TYPE_STRSIZE].fetch[i];
456
457         WARN_ON(1);     /* This should not happen */
458         return NULL;
459 }
460
461 /**
462  * Kprobe event core functions
463  */
464
465 struct probe_arg {
466         struct fetch_param      fetch;
467         struct fetch_param      fetch_size;
468         unsigned int            offset; /* Offset from argument entry */
469         const char              *name;  /* Name of this argument */
470         const char              *comm;  /* Command of this argument */
471         const struct fetch_type *type;  /* Type of this argument */
472 };
473
474 /* Flags for trace_probe */
475 #define TP_FLAG_TRACE   1
476 #define TP_FLAG_PROFILE 2
477
478 struct trace_probe {
479         struct list_head        list;
480         struct kretprobe        rp;     /* Use rp.kp for kprobe use */
481         unsigned long           nhit;
482         unsigned int            flags;  /* For TP_FLAG_* */
483         const char              *symbol;        /* symbol name */
484         struct ftrace_event_class       class;
485         struct ftrace_event_call        call;
486         ssize_t                 size;           /* trace entry size */
487         unsigned int            nr_args;
488         struct probe_arg        args[];
489 };
490
491 #define SIZEOF_TRACE_PROBE(n)                   \
492         (offsetof(struct trace_probe, args) +   \
493         (sizeof(struct probe_arg) * (n)))
494
495
496 static __kprobes int probe_is_return(struct trace_probe *tp)
497 {
498         return tp->rp.handler != NULL;
499 }
500
501 static __kprobes const char *probe_symbol(struct trace_probe *tp)
502 {
503         return tp->symbol ? tp->symbol : "unknown";
504 }
505
506 static int register_probe_event(struct trace_probe *tp);
507 static void unregister_probe_event(struct trace_probe *tp);
508
509 static DEFINE_MUTEX(probe_lock);
510 static LIST_HEAD(probe_list);
511
512 static int kprobe_dispatcher(struct kprobe *kp, struct pt_regs *regs);
513 static int kretprobe_dispatcher(struct kretprobe_instance *ri,
514                                 struct pt_regs *regs);
515
516 /* Check the name is good for event/group/fields */
517 static int is_good_name(const char *name)
518 {
519         if (!isalpha(*name) && *name != '_')
520                 return 0;
521         while (*++name != '\0') {
522                 if (!isalpha(*name) && !isdigit(*name) && *name != '_')
523                         return 0;
524         }
525         return 1;
526 }
527
528 /*
529  * Allocate new trace_probe and initialize it (including kprobes).
530  */
531 static struct trace_probe *alloc_trace_probe(const char *group,
532                                              const char *event,
533                                              void *addr,
534                                              const char *symbol,
535                                              unsigned long offs,
536                                              int nargs, int is_return)
537 {
538         struct trace_probe *tp;
539         int ret = -ENOMEM;
540
541         tp = kzalloc(SIZEOF_TRACE_PROBE(nargs), GFP_KERNEL);
542         if (!tp)
543                 return ERR_PTR(ret);
544
545         if (symbol) {
546                 tp->symbol = kstrdup(symbol, GFP_KERNEL);
547                 if (!tp->symbol)
548                         goto error;
549                 tp->rp.kp.symbol_name = tp->symbol;
550                 tp->rp.kp.offset = offs;
551         } else
552                 tp->rp.kp.addr = addr;
553
554         if (is_return)
555                 tp->rp.handler = kretprobe_dispatcher;
556         else
557                 tp->rp.kp.pre_handler = kprobe_dispatcher;
558
559         if (!event || !is_good_name(event)) {
560                 ret = -EINVAL;
561                 goto error;
562         }
563
564         tp->call.class = &tp->class;
565         tp->call.name = kstrdup(event, GFP_KERNEL);
566         if (!tp->call.name)
567                 goto error;
568
569         if (!group || !is_good_name(group)) {
570                 ret = -EINVAL;
571                 goto error;
572         }
573
574         tp->class.system = kstrdup(group, GFP_KERNEL);
575         if (!tp->class.system)
576                 goto error;
577
578         INIT_LIST_HEAD(&tp->list);
579         return tp;
580 error:
581         kfree(tp->call.name);
582         kfree(tp->symbol);
583         kfree(tp);
584         return ERR_PTR(ret);
585 }
586
587 static void free_probe_arg(struct probe_arg *arg)
588 {
589         if (CHECK_FETCH_FUNCS(deref, arg->fetch.fn))
590                 free_deref_fetch_param(arg->fetch.data);
591         else if (CHECK_FETCH_FUNCS(symbol, arg->fetch.fn))
592                 free_symbol_cache(arg->fetch.data);
593         kfree(arg->name);
594         kfree(arg->comm);
595 }
596
597 static void free_trace_probe(struct trace_probe *tp)
598 {
599         int i;
600
601         for (i = 0; i < tp->nr_args; i++)
602                 free_probe_arg(&tp->args[i]);
603
604         kfree(tp->call.class->system);
605         kfree(tp->call.name);
606         kfree(tp->symbol);
607         kfree(tp);
608 }
609
610 static struct trace_probe *find_probe_event(const char *event,
611                                             const char *group)
612 {
613         struct trace_probe *tp;
614
615         list_for_each_entry(tp, &probe_list, list)
616                 if (strcmp(tp->call.name, event) == 0 &&
617                     strcmp(tp->call.class->system, group) == 0)
618                         return tp;
619         return NULL;
620 }
621
622 /* Unregister a trace_probe and probe_event: call with locking probe_lock */
623 static void unregister_trace_probe(struct trace_probe *tp)
624 {
625         if (probe_is_return(tp))
626                 unregister_kretprobe(&tp->rp);
627         else
628                 unregister_kprobe(&tp->rp.kp);
629         list_del(&tp->list);
630         unregister_probe_event(tp);
631 }
632
633 /* Register a trace_probe and probe_event */
634 static int register_trace_probe(struct trace_probe *tp)
635 {
636         struct trace_probe *old_tp;
637         int ret;
638
639         mutex_lock(&probe_lock);
640
641         /* register as an event */
642         old_tp = find_probe_event(tp->call.name, tp->call.class->system);
643         if (old_tp) {
644                 /* delete old event */
645                 unregister_trace_probe(old_tp);
646                 free_trace_probe(old_tp);
647         }
648         ret = register_probe_event(tp);
649         if (ret) {
650                 pr_warning("Failed to register probe event(%d)\n", ret);
651                 goto end;
652         }
653
654         tp->rp.kp.flags |= KPROBE_FLAG_DISABLED;
655         if (probe_is_return(tp))
656                 ret = register_kretprobe(&tp->rp);
657         else
658                 ret = register_kprobe(&tp->rp.kp);
659
660         if (ret) {
661                 pr_warning("Could not insert probe(%d)\n", ret);
662                 if (ret == -EILSEQ) {
663                         pr_warning("Probing address(0x%p) is not an "
664                                    "instruction boundary.\n",
665                                    tp->rp.kp.addr);
666                         ret = -EINVAL;
667                 }
668                 unregister_probe_event(tp);
669         } else
670                 list_add_tail(&tp->list, &probe_list);
671 end:
672         mutex_unlock(&probe_lock);
673         return ret;
674 }
675
676 /* Split symbol and offset. */
677 static int split_symbol_offset(char *symbol, unsigned long *offset)
678 {
679         char *tmp;
680         int ret;
681
682         if (!offset)
683                 return -EINVAL;
684
685         tmp = strchr(symbol, '+');
686         if (tmp) {
687                 /* skip sign because strict_strtol doesn't accept '+' */
688                 ret = strict_strtoul(tmp + 1, 0, offset);
689                 if (ret)
690                         return ret;
691                 *tmp = '\0';
692         } else
693                 *offset = 0;
694         return 0;
695 }
696
697 #define PARAM_MAX_ARGS 16
698 #define PARAM_MAX_STACK (THREAD_SIZE / sizeof(unsigned long))
699
700 static int parse_probe_vars(char *arg, const struct fetch_type *t,
701                             struct fetch_param *f, int is_return)
702 {
703         int ret = 0;
704         unsigned long param;
705
706         if (strcmp(arg, "retval") == 0) {
707                 if (is_return)
708                         f->fn = t->fetch[FETCH_MTD_retval];
709                 else
710                         ret = -EINVAL;
711         } else if (strncmp(arg, "stack", 5) == 0) {
712                 if (arg[5] == '\0') {
713                         if (strcmp(t->name, DEFAULT_FETCH_TYPE_STR) == 0)
714                                 f->fn = fetch_stack_address;
715                         else
716                                 ret = -EINVAL;
717                 } else if (isdigit(arg[5])) {
718                         ret = strict_strtoul(arg + 5, 10, &param);
719                         if (ret || param > PARAM_MAX_STACK)
720                                 ret = -EINVAL;
721                         else {
722                                 f->fn = t->fetch[FETCH_MTD_stack];
723                                 f->data = (void *)param;
724                         }
725                 } else
726                         ret = -EINVAL;
727         } else
728                 ret = -EINVAL;
729         return ret;
730 }
731
732 /* Recursive argument parser */
733 static int __parse_probe_arg(char *arg, const struct fetch_type *t,
734                              struct fetch_param *f, int is_return)
735 {
736         int ret = 0;
737         unsigned long param;
738         long offset;
739         char *tmp;
740
741         switch (arg[0]) {
742         case '$':
743                 ret = parse_probe_vars(arg + 1, t, f, is_return);
744                 break;
745         case '%':       /* named register */
746                 ret = regs_query_register_offset(arg + 1);
747                 if (ret >= 0) {
748                         f->fn = t->fetch[FETCH_MTD_reg];
749                         f->data = (void *)(unsigned long)ret;
750                         ret = 0;
751                 }
752                 break;
753         case '@':       /* memory or symbol */
754                 if (isdigit(arg[1])) {
755                         ret = strict_strtoul(arg + 1, 0, &param);
756                         if (ret)
757                                 break;
758                         f->fn = t->fetch[FETCH_MTD_memory];
759                         f->data = (void *)param;
760                 } else {
761                         ret = split_symbol_offset(arg + 1, &offset);
762                         if (ret)
763                                 break;
764                         f->data = alloc_symbol_cache(arg + 1, offset);
765                         if (f->data)
766                                 f->fn = t->fetch[FETCH_MTD_symbol];
767                 }
768                 break;
769         case '+':       /* deref memory */
770                 arg++;  /* Skip '+', because strict_strtol() rejects it. */
771         case '-':
772                 tmp = strchr(arg, '(');
773                 if (!tmp)
774                         break;
775                 *tmp = '\0';
776                 ret = strict_strtol(arg, 0, &offset);
777                 if (ret)
778                         break;
779                 arg = tmp + 1;
780                 tmp = strrchr(arg, ')');
781                 if (tmp) {
782                         struct deref_fetch_param *dprm;
783                         const struct fetch_type *t2 = find_fetch_type(NULL);
784                         *tmp = '\0';
785                         dprm = kzalloc(sizeof(struct deref_fetch_param),
786                                        GFP_KERNEL);
787                         if (!dprm)
788                                 return -ENOMEM;
789                         dprm->offset = offset;
790                         ret = __parse_probe_arg(arg, t2, &dprm->orig,
791                                                 is_return);
792                         if (ret)
793                                 kfree(dprm);
794                         else {
795                                 f->fn = t->fetch[FETCH_MTD_deref];
796                                 f->data = (void *)dprm;
797                         }
798                 }
799                 break;
800         }
801         if (!ret && !f->fn) {   /* Parsed, but do not find fetch method */
802                 pr_info("%s type has no corresponding fetch method.\n",
803                         t->name);
804                 ret = -EINVAL;
805         }
806         return ret;
807 }
808
809 /* String length checking wrapper */
810 static int parse_probe_arg(char *arg, struct trace_probe *tp,
811                            struct probe_arg *parg, int is_return)
812 {
813         const char *t;
814         int ret;
815
816         if (strlen(arg) > MAX_ARGSTR_LEN) {
817                 pr_info("Argument is too long.: %s\n",  arg);
818                 return -ENOSPC;
819         }
820         parg->comm = kstrdup(arg, GFP_KERNEL);
821         if (!parg->comm) {
822                 pr_info("Failed to allocate memory for command '%s'.\n", arg);
823                 return -ENOMEM;
824         }
825         t = strchr(parg->comm, ':');
826         if (t) {
827                 arg[t - parg->comm] = '\0';
828                 t++;
829         }
830         parg->type = find_fetch_type(t);
831         if (!parg->type) {
832                 pr_info("Unsupported type: %s\n", t);
833                 return -EINVAL;
834         }
835         parg->offset = tp->size;
836         tp->size += parg->type->size;
837         ret = __parse_probe_arg(arg, parg->type, &parg->fetch, is_return);
838         if (ret >= 0) {
839                 parg->fetch_size.fn = get_fetch_size_function(parg->type,
840                                                               parg->fetch.fn);
841                 parg->fetch_size.data = parg->fetch.data;
842         }
843         return ret;
844 }
845
846 /* Return 1 if name is reserved or already used by another argument */
847 static int conflict_field_name(const char *name,
848                                struct probe_arg *args, int narg)
849 {
850         int i;
851         for (i = 0; i < ARRAY_SIZE(reserved_field_names); i++)
852                 if (strcmp(reserved_field_names[i], name) == 0)
853                         return 1;
854         for (i = 0; i < narg; i++)
855                 if (strcmp(args[i].name, name) == 0)
856                         return 1;
857         return 0;
858 }
859
860 static int create_trace_probe(int argc, char **argv)
861 {
862         /*
863          * Argument syntax:
864          *  - Add kprobe: p[:[GRP/]EVENT] KSYM[+OFFS]|KADDR [FETCHARGS]
865          *  - Add kretprobe: r[:[GRP/]EVENT] KSYM[+0] [FETCHARGS]
866          * Fetch args:
867          *  $retval     : fetch return value
868          *  $stack      : fetch stack address
869          *  $stackN     : fetch Nth of stack (N:0-)
870          *  @ADDR       : fetch memory at ADDR (ADDR should be in kernel)
871          *  @SYM[+|-offs] : fetch memory at SYM +|- offs (SYM is a data symbol)
872          *  %REG        : fetch register REG
873          * Dereferencing memory fetch:
874          *  +|-offs(ARG) : fetch memory at ARG +|- offs address.
875          * Alias name of args:
876          *  NAME=FETCHARG : set NAME as alias of FETCHARG.
877          * Type of args:
878          *  FETCHARG:TYPE : use TYPE instead of unsigned long.
879          */
880         struct trace_probe *tp;
881         int i, ret = 0;
882         int is_return = 0, is_delete = 0;
883         char *symbol = NULL, *event = NULL, *group = NULL;
884         char *arg;
885         unsigned long offset = 0;
886         void *addr = NULL;
887         char buf[MAX_EVENT_NAME_LEN];
888
889         /* argc must be >= 1 */
890         if (argv[0][0] == 'p')
891                 is_return = 0;
892         else if (argv[0][0] == 'r')
893                 is_return = 1;
894         else if (argv[0][0] == '-')
895                 is_delete = 1;
896         else {
897                 pr_info("Probe definition must be started with 'p', 'r' or"
898                         " '-'.\n");
899                 return -EINVAL;
900         }
901
902         if (argv[0][1] == ':') {
903                 event = &argv[0][2];
904                 if (strchr(event, '/')) {
905                         group = event;
906                         event = strchr(group, '/') + 1;
907                         event[-1] = '\0';
908                         if (strlen(group) == 0) {
909                                 pr_info("Group name is not specified\n");
910                                 return -EINVAL;
911                         }
912                 }
913                 if (strlen(event) == 0) {
914                         pr_info("Event name is not specified\n");
915                         return -EINVAL;
916                 }
917         }
918         if (!group)
919                 group = KPROBE_EVENT_SYSTEM;
920
921         if (is_delete) {
922                 if (!event) {
923                         pr_info("Delete command needs an event name.\n");
924                         return -EINVAL;
925                 }
926                 mutex_lock(&probe_lock);
927                 tp = find_probe_event(event, group);
928                 if (!tp) {
929                         mutex_unlock(&probe_lock);
930                         pr_info("Event %s/%s doesn't exist.\n", group, event);
931                         return -ENOENT;
932                 }
933                 /* delete an event */
934                 unregister_trace_probe(tp);
935                 free_trace_probe(tp);
936                 mutex_unlock(&probe_lock);
937                 return 0;
938         }
939
940         if (argc < 2) {
941                 pr_info("Probe point is not specified.\n");
942                 return -EINVAL;
943         }
944         if (isdigit(argv[1][0])) {
945                 if (is_return) {
946                         pr_info("Return probe point must be a symbol.\n");
947                         return -EINVAL;
948                 }
949                 /* an address specified */
950                 ret = strict_strtoul(&argv[1][0], 0, (unsigned long *)&addr);
951                 if (ret) {
952                         pr_info("Failed to parse address.\n");
953                         return ret;
954                 }
955         } else {
956                 /* a symbol specified */
957                 symbol = argv[1];
958                 /* TODO: support .init module functions */
959                 ret = split_symbol_offset(symbol, &offset);
960                 if (ret) {
961                         pr_info("Failed to parse symbol.\n");
962                         return ret;
963                 }
964                 if (offset && is_return) {
965                         pr_info("Return probe must be used without offset.\n");
966                         return -EINVAL;
967                 }
968         }
969         argc -= 2; argv += 2;
970
971         /* setup a probe */
972         if (!event) {
973                 /* Make a new event name */
974                 if (symbol)
975                         snprintf(buf, MAX_EVENT_NAME_LEN, "%c_%s_%ld",
976                                  is_return ? 'r' : 'p', symbol, offset);
977                 else
978                         snprintf(buf, MAX_EVENT_NAME_LEN, "%c_0x%p",
979                                  is_return ? 'r' : 'p', addr);
980                 event = buf;
981         }
982         tp = alloc_trace_probe(group, event, addr, symbol, offset, argc,
983                                is_return);
984         if (IS_ERR(tp)) {
985                 pr_info("Failed to allocate trace_probe.(%d)\n",
986                         (int)PTR_ERR(tp));
987                 return PTR_ERR(tp);
988         }
989
990         /* parse arguments */
991         ret = 0;
992         for (i = 0; i < argc && i < MAX_TRACE_ARGS; i++) {
993                 /* Increment count for freeing args in error case */
994                 tp->nr_args++;
995
996                 /* Parse argument name */
997                 arg = strchr(argv[i], '=');
998                 if (arg) {
999                         *arg++ = '\0';
1000                         tp->args[i].name = kstrdup(argv[i], GFP_KERNEL);
1001                 } else {
1002                         arg = argv[i];
1003                         /* If argument name is omitted, set "argN" */
1004                         snprintf(buf, MAX_EVENT_NAME_LEN, "arg%d", i + 1);
1005                         tp->args[i].name = kstrdup(buf, GFP_KERNEL);
1006                 }
1007
1008                 if (!tp->args[i].name) {
1009                         pr_info("Failed to allocate argument[%d] name.\n", i);
1010                         ret = -ENOMEM;
1011                         goto error;
1012                 }
1013
1014                 if (!is_good_name(tp->args[i].name)) {
1015                         pr_info("Invalid argument[%d] name: %s\n",
1016                                 i, tp->args[i].name);
1017                         ret = -EINVAL;
1018                         goto error;
1019                 }
1020
1021                 if (conflict_field_name(tp->args[i].name, tp->args, i)) {
1022                         pr_info("Argument[%d] name '%s' conflicts with "
1023                                 "another field.\n", i, argv[i]);
1024                         ret = -EINVAL;
1025                         goto error;
1026                 }
1027
1028                 /* Parse fetch argument */
1029                 ret = parse_probe_arg(arg, tp, &tp->args[i], is_return);
1030                 if (ret) {
1031                         pr_info("Parse error at argument[%d]. (%d)\n", i, ret);
1032                         goto error;
1033                 }
1034         }
1035
1036         ret = register_trace_probe(tp);
1037         if (ret)
1038                 goto error;
1039         return 0;
1040
1041 error:
1042         free_trace_probe(tp);
1043         return ret;
1044 }
1045
1046 static void cleanup_all_probes(void)
1047 {
1048         struct trace_probe *tp;
1049
1050         mutex_lock(&probe_lock);
1051         /* TODO: Use batch unregistration */
1052         while (!list_empty(&probe_list)) {
1053                 tp = list_entry(probe_list.next, struct trace_probe, list);
1054                 unregister_trace_probe(tp);
1055                 free_trace_probe(tp);
1056         }
1057         mutex_unlock(&probe_lock);
1058 }
1059
1060
1061 /* Probes listing interfaces */
1062 static void *probes_seq_start(struct seq_file *m, loff_t *pos)
1063 {
1064         mutex_lock(&probe_lock);
1065         return seq_list_start(&probe_list, *pos);
1066 }
1067
1068 static void *probes_seq_next(struct seq_file *m, void *v, loff_t *pos)
1069 {
1070         return seq_list_next(v, &probe_list, pos);
1071 }
1072
1073 static void probes_seq_stop(struct seq_file *m, void *v)
1074 {
1075         mutex_unlock(&probe_lock);
1076 }
1077
1078 static int probes_seq_show(struct seq_file *m, void *v)
1079 {
1080         struct trace_probe *tp = v;
1081         int i;
1082
1083         seq_printf(m, "%c", probe_is_return(tp) ? 'r' : 'p');
1084         seq_printf(m, ":%s/%s", tp->call.class->system, tp->call.name);
1085
1086         if (!tp->symbol)
1087                 seq_printf(m, " 0x%p", tp->rp.kp.addr);
1088         else if (tp->rp.kp.offset)
1089                 seq_printf(m, " %s+%u", probe_symbol(tp), tp->rp.kp.offset);
1090         else
1091                 seq_printf(m, " %s", probe_symbol(tp));
1092
1093         for (i = 0; i < tp->nr_args; i++)
1094                 seq_printf(m, " %s=%s", tp->args[i].name, tp->args[i].comm);
1095         seq_printf(m, "\n");
1096
1097         return 0;
1098 }
1099
1100 static const struct seq_operations probes_seq_op = {
1101         .start  = probes_seq_start,
1102         .next   = probes_seq_next,
1103         .stop   = probes_seq_stop,
1104         .show   = probes_seq_show
1105 };
1106
1107 static int probes_open(struct inode *inode, struct file *file)
1108 {
1109         if ((file->f_mode & FMODE_WRITE) &&
1110             (file->f_flags & O_TRUNC))
1111                 cleanup_all_probes();
1112
1113         return seq_open(file, &probes_seq_op);
1114 }
1115
1116 static int command_trace_probe(const char *buf)
1117 {
1118         char **argv;
1119         int argc = 0, ret = 0;
1120
1121         argv = argv_split(GFP_KERNEL, buf, &argc);
1122         if (!argv)
1123                 return -ENOMEM;
1124
1125         if (argc)
1126                 ret = create_trace_probe(argc, argv);
1127
1128         argv_free(argv);
1129         return ret;
1130 }
1131
1132 #define WRITE_BUFSIZE 128
1133
1134 static ssize_t probes_write(struct file *file, const char __user *buffer,
1135                             size_t count, loff_t *ppos)
1136 {
1137         char *kbuf, *tmp;
1138         int ret;
1139         size_t done;
1140         size_t size;
1141
1142         kbuf = kmalloc(WRITE_BUFSIZE, GFP_KERNEL);
1143         if (!kbuf)
1144                 return -ENOMEM;
1145
1146         ret = done = 0;
1147         while (done < count) {
1148                 size = count - done;
1149                 if (size >= WRITE_BUFSIZE)
1150                         size = WRITE_BUFSIZE - 1;
1151                 if (copy_from_user(kbuf, buffer + done, size)) {
1152                         ret = -EFAULT;
1153                         goto out;
1154                 }
1155                 kbuf[size] = '\0';
1156                 tmp = strchr(kbuf, '\n');
1157                 if (tmp) {
1158                         *tmp = '\0';
1159                         size = tmp - kbuf + 1;
1160                 } else if (done + size < count) {
1161                         pr_warning("Line length is too long: "
1162                                    "Should be less than %d.", WRITE_BUFSIZE);
1163                         ret = -EINVAL;
1164                         goto out;
1165                 }
1166                 done += size;
1167                 /* Remove comments */
1168                 tmp = strchr(kbuf, '#');
1169                 if (tmp)
1170                         *tmp = '\0';
1171
1172                 ret = command_trace_probe(kbuf);
1173                 if (ret)
1174                         goto out;
1175         }
1176         ret = done;
1177 out:
1178         kfree(kbuf);
1179         return ret;
1180 }
1181
1182 static const struct file_operations kprobe_events_ops = {
1183         .owner          = THIS_MODULE,
1184         .open           = probes_open,
1185         .read           = seq_read,
1186         .llseek         = seq_lseek,
1187         .release        = seq_release,
1188         .write          = probes_write,
1189 };
1190
1191 /* Probes profiling interfaces */
1192 static int probes_profile_seq_show(struct seq_file *m, void *v)
1193 {
1194         struct trace_probe *tp = v;
1195
1196         seq_printf(m, "  %-44s %15lu %15lu\n", tp->call.name, tp->nhit,
1197                    tp->rp.kp.nmissed);
1198
1199         return 0;
1200 }
1201
1202 static const struct seq_operations profile_seq_op = {
1203         .start  = probes_seq_start,
1204         .next   = probes_seq_next,
1205         .stop   = probes_seq_stop,
1206         .show   = probes_profile_seq_show
1207 };
1208
1209 static int profile_open(struct inode *inode, struct file *file)
1210 {
1211         return seq_open(file, &profile_seq_op);
1212 }
1213
1214 static const struct file_operations kprobe_profile_ops = {
1215         .owner          = THIS_MODULE,
1216         .open           = profile_open,
1217         .read           = seq_read,
1218         .llseek         = seq_lseek,
1219         .release        = seq_release,
1220 };
1221
1222 /* Sum up total data length for dynamic arraies (strings) */
1223 static __kprobes int __get_data_size(struct trace_probe *tp,
1224                                      struct pt_regs *regs)
1225 {
1226         int i, ret = 0;
1227         u32 len;
1228
1229         for (i = 0; i < tp->nr_args; i++)
1230                 if (unlikely(tp->args[i].fetch_size.fn)) {
1231                         call_fetch(&tp->args[i].fetch_size, regs, &len);
1232                         ret += len;
1233                 }
1234
1235         return ret;
1236 }
1237
1238 /* Store the value of each argument */
1239 static __kprobes void store_trace_args(int ent_size, struct trace_probe *tp,
1240                                        struct pt_regs *regs,
1241                                        u8 *data, int maxlen)
1242 {
1243         int i;
1244         u32 end = tp->size;
1245         u32 *dl;        /* Data (relative) location */
1246
1247         for (i = 0; i < tp->nr_args; i++) {
1248                 if (unlikely(tp->args[i].fetch_size.fn)) {
1249                         /*
1250                          * First, we set the relative location and
1251                          * maximum data length to *dl
1252                          */
1253                         dl = (u32 *)(data + tp->args[i].offset);
1254                         *dl = make_data_rloc(maxlen, end - tp->args[i].offset);
1255                         /* Then try to fetch string or dynamic array data */
1256                         call_fetch(&tp->args[i].fetch, regs, dl);
1257                         /* Reduce maximum length */
1258                         end += get_rloc_len(*dl);
1259                         maxlen -= get_rloc_len(*dl);
1260                         /* Trick here, convert data_rloc to data_loc */
1261                         *dl = convert_rloc_to_loc(*dl,
1262                                  ent_size + tp->args[i].offset);
1263                 } else
1264                         /* Just fetching data normally */
1265                         call_fetch(&tp->args[i].fetch, regs,
1266                                    data + tp->args[i].offset);
1267         }
1268 }
1269
1270 /* Kprobe handler */
1271 static __kprobes void kprobe_trace_func(struct kprobe *kp, struct pt_regs *regs)
1272 {
1273         struct trace_probe *tp = container_of(kp, struct trace_probe, rp.kp);
1274         struct kprobe_trace_entry_head *entry;
1275         struct ring_buffer_event *event;
1276         struct ring_buffer *buffer;
1277         int size, dsize, pc;
1278         unsigned long irq_flags;
1279         struct ftrace_event_call *call = &tp->call;
1280
1281         tp->nhit++;
1282
1283         local_save_flags(irq_flags);
1284         pc = preempt_count();
1285
1286         dsize = __get_data_size(tp, regs);
1287         size = sizeof(*entry) + tp->size + dsize;
1288
1289         event = trace_current_buffer_lock_reserve(&buffer, call->event.type,
1290                                                   size, irq_flags, pc);
1291         if (!event)
1292                 return;
1293
1294         entry = ring_buffer_event_data(event);
1295         entry->ip = (unsigned long)kp->addr;
1296         store_trace_args(sizeof(*entry), tp, regs, (u8 *)&entry[1], dsize);
1297
1298         if (!filter_current_check_discard(buffer, call, entry, event))
1299                 trace_nowake_buffer_unlock_commit(buffer, event, irq_flags, pc);
1300 }
1301
1302 /* Kretprobe handler */
1303 static __kprobes void kretprobe_trace_func(struct kretprobe_instance *ri,
1304                                           struct pt_regs *regs)
1305 {
1306         struct trace_probe *tp = container_of(ri->rp, struct trace_probe, rp);
1307         struct kretprobe_trace_entry_head *entry;
1308         struct ring_buffer_event *event;
1309         struct ring_buffer *buffer;
1310         int size, pc, dsize;
1311         unsigned long irq_flags;
1312         struct ftrace_event_call *call = &tp->call;
1313
1314         local_save_flags(irq_flags);
1315         pc = preempt_count();
1316
1317         dsize = __get_data_size(tp, regs);
1318         size = sizeof(*entry) + tp->size + dsize;
1319
1320         event = trace_current_buffer_lock_reserve(&buffer, call->event.type,
1321                                                   size, irq_flags, pc);
1322         if (!event)
1323                 return;
1324
1325         entry = ring_buffer_event_data(event);
1326         entry->func = (unsigned long)tp->rp.kp.addr;
1327         entry->ret_ip = (unsigned long)ri->ret_addr;
1328         store_trace_args(sizeof(*entry), tp, regs, (u8 *)&entry[1], dsize);
1329
1330         if (!filter_current_check_discard(buffer, call, entry, event))
1331                 trace_nowake_buffer_unlock_commit(buffer, event, irq_flags, pc);
1332 }
1333
1334 /* Event entry printers */
1335 enum print_line_t
1336 print_kprobe_event(struct trace_iterator *iter, int flags,
1337                    struct trace_event *event)
1338 {
1339         struct kprobe_trace_entry_head *field;
1340         struct trace_seq *s = &iter->seq;
1341         struct trace_probe *tp;
1342         u8 *data;
1343         int i;
1344
1345         field = (struct kprobe_trace_entry_head *)iter->ent;
1346         tp = container_of(event, struct trace_probe, call.event);
1347
1348         if (!trace_seq_printf(s, "%s: (", tp->call.name))
1349                 goto partial;
1350
1351         if (!seq_print_ip_sym(s, field->ip, flags | TRACE_ITER_SYM_OFFSET))
1352                 goto partial;
1353
1354         if (!trace_seq_puts(s, ")"))
1355                 goto partial;
1356
1357         data = (u8 *)&field[1];
1358         for (i = 0; i < tp->nr_args; i++)
1359                 if (!tp->args[i].type->print(s, tp->args[i].name,
1360                                              data + tp->args[i].offset, field))
1361                         goto partial;
1362
1363         if (!trace_seq_puts(s, "\n"))
1364                 goto partial;
1365
1366         return TRACE_TYPE_HANDLED;
1367 partial:
1368         return TRACE_TYPE_PARTIAL_LINE;
1369 }
1370
1371 enum print_line_t
1372 print_kretprobe_event(struct trace_iterator *iter, int flags,
1373                       struct trace_event *event)
1374 {
1375         struct kretprobe_trace_entry_head *field;
1376         struct trace_seq *s = &iter->seq;
1377         struct trace_probe *tp;
1378         u8 *data;
1379         int i;
1380
1381         field = (struct kretprobe_trace_entry_head *)iter->ent;
1382         tp = container_of(event, struct trace_probe, call.event);
1383
1384         if (!trace_seq_printf(s, "%s: (", tp->call.name))
1385                 goto partial;
1386
1387         if (!seq_print_ip_sym(s, field->ret_ip, flags | TRACE_ITER_SYM_OFFSET))
1388                 goto partial;
1389
1390         if (!trace_seq_puts(s, " <- "))
1391                 goto partial;
1392
1393         if (!seq_print_ip_sym(s, field->func, flags & ~TRACE_ITER_SYM_OFFSET))
1394                 goto partial;
1395
1396         if (!trace_seq_puts(s, ")"))
1397                 goto partial;
1398
1399         data = (u8 *)&field[1];
1400         for (i = 0; i < tp->nr_args; i++)
1401                 if (!tp->args[i].type->print(s, tp->args[i].name,
1402                                              data + tp->args[i].offset, field))
1403                         goto partial;
1404
1405         if (!trace_seq_puts(s, "\n"))
1406                 goto partial;
1407
1408         return TRACE_TYPE_HANDLED;
1409 partial:
1410         return TRACE_TYPE_PARTIAL_LINE;
1411 }
1412
1413 static int probe_event_enable(struct ftrace_event_call *call)
1414 {
1415         struct trace_probe *tp = (struct trace_probe *)call->data;
1416
1417         tp->flags |= TP_FLAG_TRACE;
1418         if (probe_is_return(tp))
1419                 return enable_kretprobe(&tp->rp);
1420         else
1421                 return enable_kprobe(&tp->rp.kp);
1422 }
1423
1424 static void probe_event_disable(struct ftrace_event_call *call)
1425 {
1426         struct trace_probe *tp = (struct trace_probe *)call->data;
1427
1428         tp->flags &= ~TP_FLAG_TRACE;
1429         if (!(tp->flags & (TP_FLAG_TRACE | TP_FLAG_PROFILE))) {
1430                 if (probe_is_return(tp))
1431                         disable_kretprobe(&tp->rp);
1432                 else
1433                         disable_kprobe(&tp->rp.kp);
1434         }
1435 }
1436
1437 #undef DEFINE_FIELD
1438 #define DEFINE_FIELD(type, item, name, is_signed)                       \
1439         do {                                                            \
1440                 ret = trace_define_field(event_call, #type, name,       \
1441                                          offsetof(typeof(field), item), \
1442                                          sizeof(field.item), is_signed, \
1443                                          FILTER_OTHER);                 \
1444                 if (ret)                                                \
1445                         return ret;                                     \
1446         } while (0)
1447
1448 static int kprobe_event_define_fields(struct ftrace_event_call *event_call)
1449 {
1450         int ret, i;
1451         struct kprobe_trace_entry_head field;
1452         struct trace_probe *tp = (struct trace_probe *)event_call->data;
1453
1454         DEFINE_FIELD(unsigned long, ip, FIELD_STRING_IP, 0);
1455         /* Set argument names as fields */
1456         for (i = 0; i < tp->nr_args; i++) {
1457                 ret = trace_define_field(event_call, tp->args[i].type->fmttype,
1458                                          tp->args[i].name,
1459                                          sizeof(field) + tp->args[i].offset,
1460                                          tp->args[i].type->size,
1461                                          tp->args[i].type->is_signed,
1462                                          FILTER_OTHER);
1463                 if (ret)
1464                         return ret;
1465         }
1466         return 0;
1467 }
1468
1469 static int kretprobe_event_define_fields(struct ftrace_event_call *event_call)
1470 {
1471         int ret, i;
1472         struct kretprobe_trace_entry_head field;
1473         struct trace_probe *tp = (struct trace_probe *)event_call->data;
1474
1475         DEFINE_FIELD(unsigned long, func, FIELD_STRING_FUNC, 0);
1476         DEFINE_FIELD(unsigned long, ret_ip, FIELD_STRING_RETIP, 0);
1477         /* Set argument names as fields */
1478         for (i = 0; i < tp->nr_args; i++) {
1479                 ret = trace_define_field(event_call, tp->args[i].type->fmttype,
1480                                          tp->args[i].name,
1481                                          sizeof(field) + tp->args[i].offset,
1482                                          tp->args[i].type->size,
1483                                          tp->args[i].type->is_signed,
1484                                          FILTER_OTHER);
1485                 if (ret)
1486                         return ret;
1487         }
1488         return 0;
1489 }
1490
1491 static int __set_print_fmt(struct trace_probe *tp, char *buf, int len)
1492 {
1493         int i;
1494         int pos = 0;
1495
1496         const char *fmt, *arg;
1497
1498         if (!probe_is_return(tp)) {
1499                 fmt = "(%lx)";
1500                 arg = "REC->" FIELD_STRING_IP;
1501         } else {
1502                 fmt = "(%lx <- %lx)";
1503                 arg = "REC->" FIELD_STRING_FUNC ", REC->" FIELD_STRING_RETIP;
1504         }
1505
1506         /* When len=0, we just calculate the needed length */
1507 #define LEN_OR_ZERO (len ? len - pos : 0)
1508
1509         pos += snprintf(buf + pos, LEN_OR_ZERO, "\"%s", fmt);
1510
1511         for (i = 0; i < tp->nr_args; i++) {
1512                 pos += snprintf(buf + pos, LEN_OR_ZERO, " %s=%s",
1513                                 tp->args[i].name, tp->args[i].type->fmt);
1514         }
1515
1516         pos += snprintf(buf + pos, LEN_OR_ZERO, "\", %s", arg);
1517
1518         for (i = 0; i < tp->nr_args; i++) {
1519                 if (strcmp(tp->args[i].type->name, "string") == 0)
1520                         pos += snprintf(buf + pos, LEN_OR_ZERO,
1521                                         ", __get_str(%s)",
1522                                         tp->args[i].name);
1523                 else
1524                         pos += snprintf(buf + pos, LEN_OR_ZERO, ", REC->%s",
1525                                         tp->args[i].name);
1526         }
1527
1528 #undef LEN_OR_ZERO
1529
1530         /* return the length of print_fmt */
1531         return pos;
1532 }
1533
1534 static int set_print_fmt(struct trace_probe *tp)
1535 {
1536         int len;
1537         char *print_fmt;
1538
1539         /* First: called with 0 length to calculate the needed length */
1540         len = __set_print_fmt(tp, NULL, 0);
1541         print_fmt = kmalloc(len + 1, GFP_KERNEL);
1542         if (!print_fmt)
1543                 return -ENOMEM;
1544
1545         /* Second: actually write the @print_fmt */
1546         __set_print_fmt(tp, print_fmt, len + 1);
1547         tp->call.print_fmt = print_fmt;
1548
1549         return 0;
1550 }
1551
1552 #ifdef CONFIG_PERF_EVENTS
1553
1554 /* Kprobe profile handler */
1555 static __kprobes void kprobe_perf_func(struct kprobe *kp,
1556                                          struct pt_regs *regs)
1557 {
1558         struct trace_probe *tp = container_of(kp, struct trace_probe, rp.kp);
1559         struct ftrace_event_call *call = &tp->call;
1560         struct kprobe_trace_entry_head *entry;
1561         struct hlist_head *head;
1562         int size, __size, dsize;
1563         int rctx;
1564
1565         dsize = __get_data_size(tp, regs);
1566         __size = sizeof(*entry) + tp->size + dsize;
1567         size = ALIGN(__size + sizeof(u32), sizeof(u64));
1568         size -= sizeof(u32);
1569         if (WARN_ONCE(size > PERF_MAX_TRACE_SIZE,
1570                      "profile buffer not large enough"))
1571                 return;
1572
1573         entry = perf_trace_buf_prepare(size, call->event.type, regs, &rctx);
1574         if (!entry)
1575                 return;
1576
1577         entry->ip = (unsigned long)kp->addr;
1578         memset(&entry[1], 0, dsize);
1579         store_trace_args(sizeof(*entry), tp, regs, (u8 *)&entry[1], dsize);
1580
1581         head = this_cpu_ptr(call->perf_events);
1582         perf_trace_buf_submit(entry, size, rctx, entry->ip, 1, regs, head);
1583 }
1584
1585 /* Kretprobe profile handler */
1586 static __kprobes void kretprobe_perf_func(struct kretprobe_instance *ri,
1587                                             struct pt_regs *regs)
1588 {
1589         struct trace_probe *tp = container_of(ri->rp, struct trace_probe, rp);
1590         struct ftrace_event_call *call = &tp->call;
1591         struct kretprobe_trace_entry_head *entry;
1592         struct hlist_head *head;
1593         int size, __size, dsize;
1594         int rctx;
1595
1596         dsize = __get_data_size(tp, regs);
1597         __size = sizeof(*entry) + tp->size + dsize;
1598         size = ALIGN(__size + sizeof(u32), sizeof(u64));
1599         size -= sizeof(u32);
1600         if (WARN_ONCE(size > PERF_MAX_TRACE_SIZE,
1601                      "profile buffer not large enough"))
1602                 return;
1603
1604         entry = perf_trace_buf_prepare(size, call->event.type, regs, &rctx);
1605         if (!entry)
1606                 return;
1607
1608         entry->func = (unsigned long)tp->rp.kp.addr;
1609         entry->ret_ip = (unsigned long)ri->ret_addr;
1610         store_trace_args(sizeof(*entry), tp, regs, (u8 *)&entry[1], dsize);
1611
1612         head = this_cpu_ptr(call->perf_events);
1613         perf_trace_buf_submit(entry, size, rctx, entry->ret_ip, 1, regs, head);
1614 }
1615
1616 static int probe_perf_enable(struct ftrace_event_call *call)
1617 {
1618         struct trace_probe *tp = (struct trace_probe *)call->data;
1619
1620         tp->flags |= TP_FLAG_PROFILE;
1621
1622         if (probe_is_return(tp))
1623                 return enable_kretprobe(&tp->rp);
1624         else
1625                 return enable_kprobe(&tp->rp.kp);
1626 }
1627
1628 static void probe_perf_disable(struct ftrace_event_call *call)
1629 {
1630         struct trace_probe *tp = (struct trace_probe *)call->data;
1631
1632         tp->flags &= ~TP_FLAG_PROFILE;
1633
1634         if (!(tp->flags & TP_FLAG_TRACE)) {
1635                 if (probe_is_return(tp))
1636                         disable_kretprobe(&tp->rp);
1637                 else
1638                         disable_kprobe(&tp->rp.kp);
1639         }
1640 }
1641 #endif  /* CONFIG_PERF_EVENTS */
1642
1643 static __kprobes
1644 int kprobe_register(struct ftrace_event_call *event, enum trace_reg type)
1645 {
1646         switch (type) {
1647         case TRACE_REG_REGISTER:
1648                 return probe_event_enable(event);
1649         case TRACE_REG_UNREGISTER:
1650                 probe_event_disable(event);
1651                 return 0;
1652
1653 #ifdef CONFIG_PERF_EVENTS
1654         case TRACE_REG_PERF_REGISTER:
1655                 return probe_perf_enable(event);
1656         case TRACE_REG_PERF_UNREGISTER:
1657                 probe_perf_disable(event);
1658                 return 0;
1659 #endif
1660         }
1661         return 0;
1662 }
1663
1664 static __kprobes
1665 int kprobe_dispatcher(struct kprobe *kp, struct pt_regs *regs)
1666 {
1667         struct trace_probe *tp = container_of(kp, struct trace_probe, rp.kp);
1668
1669         if (tp->flags & TP_FLAG_TRACE)
1670                 kprobe_trace_func(kp, regs);
1671 #ifdef CONFIG_PERF_EVENTS
1672         if (tp->flags & TP_FLAG_PROFILE)
1673                 kprobe_perf_func(kp, regs);
1674 #endif
1675         return 0;       /* We don't tweek kernel, so just return 0 */
1676 }
1677
1678 static __kprobes
1679 int kretprobe_dispatcher(struct kretprobe_instance *ri, struct pt_regs *regs)
1680 {
1681         struct trace_probe *tp = container_of(ri->rp, struct trace_probe, rp);
1682
1683         if (tp->flags & TP_FLAG_TRACE)
1684                 kretprobe_trace_func(ri, regs);
1685 #ifdef CONFIG_PERF_EVENTS
1686         if (tp->flags & TP_FLAG_PROFILE)
1687                 kretprobe_perf_func(ri, regs);
1688 #endif
1689         return 0;       /* We don't tweek kernel, so just return 0 */
1690 }
1691
1692 static struct trace_event_functions kretprobe_funcs = {
1693         .trace          = print_kretprobe_event
1694 };
1695
1696 static struct trace_event_functions kprobe_funcs = {
1697         .trace          = print_kprobe_event
1698 };
1699
1700 static int register_probe_event(struct trace_probe *tp)
1701 {
1702         struct ftrace_event_call *call = &tp->call;
1703         int ret;
1704
1705         /* Initialize ftrace_event_call */
1706         INIT_LIST_HEAD(&call->class->fields);
1707         if (probe_is_return(tp)) {
1708                 call->event.funcs = &kretprobe_funcs;
1709                 call->class->define_fields = kretprobe_event_define_fields;
1710         } else {
1711                 call->event.funcs = &kprobe_funcs;
1712                 call->class->define_fields = kprobe_event_define_fields;
1713         }
1714         if (set_print_fmt(tp) < 0)
1715                 return -ENOMEM;
1716         ret = register_ftrace_event(&call->event);
1717         if (!ret) {
1718                 kfree(call->print_fmt);
1719                 return -ENODEV;
1720         }
1721         call->flags = 0;
1722         call->class->reg = kprobe_register;
1723         call->data = tp;
1724         ret = trace_add_event_call(call);
1725         if (ret) {
1726                 pr_info("Failed to register kprobe event: %s\n", call->name);
1727                 kfree(call->print_fmt);
1728                 unregister_ftrace_event(&call->event);
1729         }
1730         return ret;
1731 }
1732
1733 static void unregister_probe_event(struct trace_probe *tp)
1734 {
1735         /* tp->event is unregistered in trace_remove_event_call() */
1736         trace_remove_event_call(&tp->call);
1737         kfree(tp->call.print_fmt);
1738 }
1739
1740 /* Make a debugfs interface for controling probe points */
1741 static __init int init_kprobe_trace(void)
1742 {
1743         struct dentry *d_tracer;
1744         struct dentry *entry;
1745
1746         d_tracer = tracing_init_dentry();
1747         if (!d_tracer)
1748                 return 0;
1749
1750         entry = debugfs_create_file("kprobe_events", 0644, d_tracer,
1751                                     NULL, &kprobe_events_ops);
1752
1753         /* Event list interface */
1754         if (!entry)
1755                 pr_warning("Could not create debugfs "
1756                            "'kprobe_events' entry\n");
1757
1758         /* Profile interface */
1759         entry = debugfs_create_file("kprobe_profile", 0444, d_tracer,
1760                                     NULL, &kprobe_profile_ops);
1761
1762         if (!entry)
1763                 pr_warning("Could not create debugfs "
1764                            "'kprobe_profile' entry\n");
1765         return 0;
1766 }
1767 fs_initcall(init_kprobe_trace);
1768
1769
1770 #ifdef CONFIG_FTRACE_STARTUP_TEST
1771
1772 static int kprobe_trace_selftest_target(int a1, int a2, int a3,
1773                                         int a4, int a5, int a6)
1774 {
1775         return a1 + a2 + a3 + a4 + a5 + a6;
1776 }
1777
1778 static __init int kprobe_trace_self_tests_init(void)
1779 {
1780         int ret, warn = 0;
1781         int (*target)(int, int, int, int, int, int);
1782         struct trace_probe *tp;
1783
1784         target = kprobe_trace_selftest_target;
1785
1786         pr_info("Testing kprobe tracing: ");
1787
1788         ret = command_trace_probe("p:testprobe kprobe_trace_selftest_target "
1789                                   "$stack $stack0 +0($stack)");
1790         if (WARN_ON_ONCE(ret)) {
1791                 pr_warning("error on probing function entry.\n");
1792                 warn++;
1793         } else {
1794                 /* Enable trace point */
1795                 tp = find_probe_event("testprobe", KPROBE_EVENT_SYSTEM);
1796                 if (WARN_ON_ONCE(tp == NULL)) {
1797                         pr_warning("error on getting new probe.\n");
1798                         warn++;
1799                 } else
1800                         probe_event_enable(&tp->call);
1801         }
1802
1803         ret = command_trace_probe("r:testprobe2 kprobe_trace_selftest_target "
1804                                   "$retval");
1805         if (WARN_ON_ONCE(ret)) {
1806                 pr_warning("error on probing function return.\n");
1807                 warn++;
1808         } else {
1809                 /* Enable trace point */
1810                 tp = find_probe_event("testprobe2", KPROBE_EVENT_SYSTEM);
1811                 if (WARN_ON_ONCE(tp == NULL)) {
1812                         pr_warning("error on getting new probe.\n");
1813                         warn++;
1814                 } else
1815                         probe_event_enable(&tp->call);
1816         }
1817
1818         if (warn)
1819                 goto end;
1820
1821         ret = target(1, 2, 3, 4, 5, 6);
1822
1823         ret = command_trace_probe("-:testprobe");
1824         if (WARN_ON_ONCE(ret)) {
1825                 pr_warning("error on deleting a probe.\n");
1826                 warn++;
1827         }
1828
1829         ret = command_trace_probe("-:testprobe2");
1830         if (WARN_ON_ONCE(ret)) {
1831                 pr_warning("error on deleting a probe.\n");
1832                 warn++;
1833         }
1834
1835 end:
1836         cleanup_all_probes();
1837         if (warn)
1838                 pr_cont("NG: Some tests are failed. Please check them.\n");
1839         else
1840                 pr_cont("OK\n");
1841         return 0;
1842 }
1843
1844 late_initcall(kprobe_trace_self_tests_init);
1845
1846 #endif