Merge tag 'tty-6.4-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/tty
[sfrench/cifs-2.6.git] / kernel / trace / ftrace.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Infrastructure for profiling code inserted by 'gcc -pg'.
4  *
5  * Copyright (C) 2007-2008 Steven Rostedt <srostedt@redhat.com>
6  * Copyright (C) 2004-2008 Ingo Molnar <mingo@redhat.com>
7  *
8  * Originally ported from the -rt patch by:
9  *   Copyright (C) 2007 Arnaldo Carvalho de Melo <acme@redhat.com>
10  *
11  * Based on code in the latency_tracer, that is:
12  *
13  *  Copyright (C) 2004-2006 Ingo Molnar
14  *  Copyright (C) 2004 Nadia Yvette Chambers
15  */
16
17 #include <linux/stop_machine.h>
18 #include <linux/clocksource.h>
19 #include <linux/sched/task.h>
20 #include <linux/kallsyms.h>
21 #include <linux/security.h>
22 #include <linux/seq_file.h>
23 #include <linux/tracefs.h>
24 #include <linux/hardirq.h>
25 #include <linux/kthread.h>
26 #include <linux/uaccess.h>
27 #include <linux/bsearch.h>
28 #include <linux/module.h>
29 #include <linux/ftrace.h>
30 #include <linux/sysctl.h>
31 #include <linux/slab.h>
32 #include <linux/ctype.h>
33 #include <linux/sort.h>
34 #include <linux/list.h>
35 #include <linux/hash.h>
36 #include <linux/rcupdate.h>
37 #include <linux/kprobes.h>
38
39 #include <trace/events/sched.h>
40
41 #include <asm/sections.h>
42 #include <asm/setup.h>
43
44 #include "ftrace_internal.h"
45 #include "trace_output.h"
46 #include "trace_stat.h"
47
48 #define FTRACE_INVALID_FUNCTION         "__ftrace_invalid_address__"
49
50 #define FTRACE_WARN_ON(cond)                    \
51         ({                                      \
52                 int ___r = cond;                \
53                 if (WARN_ON(___r))              \
54                         ftrace_kill();          \
55                 ___r;                           \
56         })
57
58 #define FTRACE_WARN_ON_ONCE(cond)               \
59         ({                                      \
60                 int ___r = cond;                \
61                 if (WARN_ON_ONCE(___r))         \
62                         ftrace_kill();          \
63                 ___r;                           \
64         })
65
66 /* hash bits for specific function selection */
67 #define FTRACE_HASH_DEFAULT_BITS 10
68 #define FTRACE_HASH_MAX_BITS 12
69
70 #ifdef CONFIG_DYNAMIC_FTRACE
71 #define INIT_OPS_HASH(opsname)  \
72         .func_hash              = &opsname.local_hash,                  \
73         .local_hash.regex_lock  = __MUTEX_INITIALIZER(opsname.local_hash.regex_lock),
74 #else
75 #define INIT_OPS_HASH(opsname)
76 #endif
77
78 enum {
79         FTRACE_MODIFY_ENABLE_FL         = (1 << 0),
80         FTRACE_MODIFY_MAY_SLEEP_FL      = (1 << 1),
81 };
82
83 struct ftrace_ops ftrace_list_end __read_mostly = {
84         .func           = ftrace_stub,
85         .flags          = FTRACE_OPS_FL_STUB,
86         INIT_OPS_HASH(ftrace_list_end)
87 };
88
89 /* ftrace_enabled is a method to turn ftrace on or off */
90 int ftrace_enabled __read_mostly;
91 static int __maybe_unused last_ftrace_enabled;
92
93 /* Current function tracing op */
94 struct ftrace_ops *function_trace_op __read_mostly = &ftrace_list_end;
95 /* What to set function_trace_op to */
96 static struct ftrace_ops *set_function_trace_op;
97
98 static bool ftrace_pids_enabled(struct ftrace_ops *ops)
99 {
100         struct trace_array *tr;
101
102         if (!(ops->flags & FTRACE_OPS_FL_PID) || !ops->private)
103                 return false;
104
105         tr = ops->private;
106
107         return tr->function_pids != NULL || tr->function_no_pids != NULL;
108 }
109
110 static void ftrace_update_trampoline(struct ftrace_ops *ops);
111
112 /*
113  * ftrace_disabled is set when an anomaly is discovered.
114  * ftrace_disabled is much stronger than ftrace_enabled.
115  */
116 static int ftrace_disabled __read_mostly;
117
118 DEFINE_MUTEX(ftrace_lock);
119
120 struct ftrace_ops __rcu *ftrace_ops_list __read_mostly = &ftrace_list_end;
121 ftrace_func_t ftrace_trace_function __read_mostly = ftrace_stub;
122 struct ftrace_ops global_ops;
123
124 /* Defined by vmlinux.lds.h see the comment above arch_ftrace_ops_list_func for details */
125 void ftrace_ops_list_func(unsigned long ip, unsigned long parent_ip,
126                           struct ftrace_ops *op, struct ftrace_regs *fregs);
127
128 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_CALL_OPS
129 /*
130  * Stub used to invoke the list ops without requiring a separate trampoline.
131  */
132 const struct ftrace_ops ftrace_list_ops = {
133         .func   = ftrace_ops_list_func,
134         .flags  = FTRACE_OPS_FL_STUB,
135 };
136
137 static void ftrace_ops_nop_func(unsigned long ip, unsigned long parent_ip,
138                                 struct ftrace_ops *op,
139                                 struct ftrace_regs *fregs)
140 {
141         /* do nothing */
142 }
143
144 /*
145  * Stub used when a call site is disabled. May be called transiently by threads
146  * which have made it into ftrace_caller but haven't yet recovered the ops at
147  * the point the call site is disabled.
148  */
149 const struct ftrace_ops ftrace_nop_ops = {
150         .func   = ftrace_ops_nop_func,
151         .flags  = FTRACE_OPS_FL_STUB,
152 };
153 #endif
154
155 static inline void ftrace_ops_init(struct ftrace_ops *ops)
156 {
157 #ifdef CONFIG_DYNAMIC_FTRACE
158         if (!(ops->flags & FTRACE_OPS_FL_INITIALIZED)) {
159                 mutex_init(&ops->local_hash.regex_lock);
160                 ops->func_hash = &ops->local_hash;
161                 ops->flags |= FTRACE_OPS_FL_INITIALIZED;
162         }
163 #endif
164 }
165
166 static void ftrace_pid_func(unsigned long ip, unsigned long parent_ip,
167                             struct ftrace_ops *op, struct ftrace_regs *fregs)
168 {
169         struct trace_array *tr = op->private;
170         int pid;
171
172         if (tr) {
173                 pid = this_cpu_read(tr->array_buffer.data->ftrace_ignore_pid);
174                 if (pid == FTRACE_PID_IGNORE)
175                         return;
176                 if (pid != FTRACE_PID_TRACE &&
177                     pid != current->pid)
178                         return;
179         }
180
181         op->saved_func(ip, parent_ip, op, fregs);
182 }
183
184 static void ftrace_sync_ipi(void *data)
185 {
186         /* Probably not needed, but do it anyway */
187         smp_rmb();
188 }
189
190 static ftrace_func_t ftrace_ops_get_list_func(struct ftrace_ops *ops)
191 {
192         /*
193          * If this is a dynamic or RCU ops, or we force list func,
194          * then it needs to call the list anyway.
195          */
196         if (ops->flags & (FTRACE_OPS_FL_DYNAMIC | FTRACE_OPS_FL_RCU) ||
197             FTRACE_FORCE_LIST_FUNC)
198                 return ftrace_ops_list_func;
199
200         return ftrace_ops_get_func(ops);
201 }
202
203 static void update_ftrace_function(void)
204 {
205         ftrace_func_t func;
206
207         /*
208          * Prepare the ftrace_ops that the arch callback will use.
209          * If there's only one ftrace_ops registered, the ftrace_ops_list
210          * will point to the ops we want.
211          */
212         set_function_trace_op = rcu_dereference_protected(ftrace_ops_list,
213                                                 lockdep_is_held(&ftrace_lock));
214
215         /* If there's no ftrace_ops registered, just call the stub function */
216         if (set_function_trace_op == &ftrace_list_end) {
217                 func = ftrace_stub;
218
219         /*
220          * If we are at the end of the list and this ops is
221          * recursion safe and not dynamic and the arch supports passing ops,
222          * then have the mcount trampoline call the function directly.
223          */
224         } else if (rcu_dereference_protected(ftrace_ops_list->next,
225                         lockdep_is_held(&ftrace_lock)) == &ftrace_list_end) {
226                 func = ftrace_ops_get_list_func(ftrace_ops_list);
227
228         } else {
229                 /* Just use the default ftrace_ops */
230                 set_function_trace_op = &ftrace_list_end;
231                 func = ftrace_ops_list_func;
232         }
233
234         update_function_graph_func();
235
236         /* If there's no change, then do nothing more here */
237         if (ftrace_trace_function == func)
238                 return;
239
240         /*
241          * If we are using the list function, it doesn't care
242          * about the function_trace_ops.
243          */
244         if (func == ftrace_ops_list_func) {
245                 ftrace_trace_function = func;
246                 /*
247                  * Don't even bother setting function_trace_ops,
248                  * it would be racy to do so anyway.
249                  */
250                 return;
251         }
252
253 #ifndef CONFIG_DYNAMIC_FTRACE
254         /*
255          * For static tracing, we need to be a bit more careful.
256          * The function change takes affect immediately. Thus,
257          * we need to coordinate the setting of the function_trace_ops
258          * with the setting of the ftrace_trace_function.
259          *
260          * Set the function to the list ops, which will call the
261          * function we want, albeit indirectly, but it handles the
262          * ftrace_ops and doesn't depend on function_trace_op.
263          */
264         ftrace_trace_function = ftrace_ops_list_func;
265         /*
266          * Make sure all CPUs see this. Yes this is slow, but static
267          * tracing is slow and nasty to have enabled.
268          */
269         synchronize_rcu_tasks_rude();
270         /* Now all cpus are using the list ops. */
271         function_trace_op = set_function_trace_op;
272         /* Make sure the function_trace_op is visible on all CPUs */
273         smp_wmb();
274         /* Nasty way to force a rmb on all cpus */
275         smp_call_function(ftrace_sync_ipi, NULL, 1);
276         /* OK, we are all set to update the ftrace_trace_function now! */
277 #endif /* !CONFIG_DYNAMIC_FTRACE */
278
279         ftrace_trace_function = func;
280 }
281
282 static void add_ftrace_ops(struct ftrace_ops __rcu **list,
283                            struct ftrace_ops *ops)
284 {
285         rcu_assign_pointer(ops->next, *list);
286
287         /*
288          * We are entering ops into the list but another
289          * CPU might be walking that list. We need to make sure
290          * the ops->next pointer is valid before another CPU sees
291          * the ops pointer included into the list.
292          */
293         rcu_assign_pointer(*list, ops);
294 }
295
296 static int remove_ftrace_ops(struct ftrace_ops __rcu **list,
297                              struct ftrace_ops *ops)
298 {
299         struct ftrace_ops **p;
300
301         /*
302          * If we are removing the last function, then simply point
303          * to the ftrace_stub.
304          */
305         if (rcu_dereference_protected(*list,
306                         lockdep_is_held(&ftrace_lock)) == ops &&
307             rcu_dereference_protected(ops->next,
308                         lockdep_is_held(&ftrace_lock)) == &ftrace_list_end) {
309                 *list = &ftrace_list_end;
310                 return 0;
311         }
312
313         for (p = list; *p != &ftrace_list_end; p = &(*p)->next)
314                 if (*p == ops)
315                         break;
316
317         if (*p != ops)
318                 return -1;
319
320         *p = (*p)->next;
321         return 0;
322 }
323
324 static void ftrace_update_trampoline(struct ftrace_ops *ops);
325
326 int __register_ftrace_function(struct ftrace_ops *ops)
327 {
328         if (ops->flags & FTRACE_OPS_FL_DELETED)
329                 return -EINVAL;
330
331         if (WARN_ON(ops->flags & FTRACE_OPS_FL_ENABLED))
332                 return -EBUSY;
333
334 #ifndef CONFIG_DYNAMIC_FTRACE_WITH_REGS
335         /*
336          * If the ftrace_ops specifies SAVE_REGS, then it only can be used
337          * if the arch supports it, or SAVE_REGS_IF_SUPPORTED is also set.
338          * Setting SAVE_REGS_IF_SUPPORTED makes SAVE_REGS irrelevant.
339          */
340         if (ops->flags & FTRACE_OPS_FL_SAVE_REGS &&
341             !(ops->flags & FTRACE_OPS_FL_SAVE_REGS_IF_SUPPORTED))
342                 return -EINVAL;
343
344         if (ops->flags & FTRACE_OPS_FL_SAVE_REGS_IF_SUPPORTED)
345                 ops->flags |= FTRACE_OPS_FL_SAVE_REGS;
346 #endif
347         if (!ftrace_enabled && (ops->flags & FTRACE_OPS_FL_PERMANENT))
348                 return -EBUSY;
349
350         if (!is_kernel_core_data((unsigned long)ops))
351                 ops->flags |= FTRACE_OPS_FL_DYNAMIC;
352
353         add_ftrace_ops(&ftrace_ops_list, ops);
354
355         /* Always save the function, and reset at unregistering */
356         ops->saved_func = ops->func;
357
358         if (ftrace_pids_enabled(ops))
359                 ops->func = ftrace_pid_func;
360
361         ftrace_update_trampoline(ops);
362
363         if (ftrace_enabled)
364                 update_ftrace_function();
365
366         return 0;
367 }
368
369 int __unregister_ftrace_function(struct ftrace_ops *ops)
370 {
371         int ret;
372
373         if (WARN_ON(!(ops->flags & FTRACE_OPS_FL_ENABLED)))
374                 return -EBUSY;
375
376         ret = remove_ftrace_ops(&ftrace_ops_list, ops);
377
378         if (ret < 0)
379                 return ret;
380
381         if (ftrace_enabled)
382                 update_ftrace_function();
383
384         ops->func = ops->saved_func;
385
386         return 0;
387 }
388
389 static void ftrace_update_pid_func(void)
390 {
391         struct ftrace_ops *op;
392
393         /* Only do something if we are tracing something */
394         if (ftrace_trace_function == ftrace_stub)
395                 return;
396
397         do_for_each_ftrace_op(op, ftrace_ops_list) {
398                 if (op->flags & FTRACE_OPS_FL_PID) {
399                         op->func = ftrace_pids_enabled(op) ?
400                                 ftrace_pid_func : op->saved_func;
401                         ftrace_update_trampoline(op);
402                 }
403         } while_for_each_ftrace_op(op);
404
405         update_ftrace_function();
406 }
407
408 #ifdef CONFIG_FUNCTION_PROFILER
409 struct ftrace_profile {
410         struct hlist_node               node;
411         unsigned long                   ip;
412         unsigned long                   counter;
413 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
414         unsigned long long              time;
415         unsigned long long              time_squared;
416 #endif
417 };
418
419 struct ftrace_profile_page {
420         struct ftrace_profile_page      *next;
421         unsigned long                   index;
422         struct ftrace_profile           records[];
423 };
424
425 struct ftrace_profile_stat {
426         atomic_t                        disabled;
427         struct hlist_head               *hash;
428         struct ftrace_profile_page      *pages;
429         struct ftrace_profile_page      *start;
430         struct tracer_stat              stat;
431 };
432
433 #define PROFILE_RECORDS_SIZE                                            \
434         (PAGE_SIZE - offsetof(struct ftrace_profile_page, records))
435
436 #define PROFILES_PER_PAGE                                       \
437         (PROFILE_RECORDS_SIZE / sizeof(struct ftrace_profile))
438
439 static int ftrace_profile_enabled __read_mostly;
440
441 /* ftrace_profile_lock - synchronize the enable and disable of the profiler */
442 static DEFINE_MUTEX(ftrace_profile_lock);
443
444 static DEFINE_PER_CPU(struct ftrace_profile_stat, ftrace_profile_stats);
445
446 #define FTRACE_PROFILE_HASH_BITS 10
447 #define FTRACE_PROFILE_HASH_SIZE (1 << FTRACE_PROFILE_HASH_BITS)
448
449 static void *
450 function_stat_next(void *v, int idx)
451 {
452         struct ftrace_profile *rec = v;
453         struct ftrace_profile_page *pg;
454
455         pg = (struct ftrace_profile_page *)((unsigned long)rec & PAGE_MASK);
456
457  again:
458         if (idx != 0)
459                 rec++;
460
461         if ((void *)rec >= (void *)&pg->records[pg->index]) {
462                 pg = pg->next;
463                 if (!pg)
464                         return NULL;
465                 rec = &pg->records[0];
466                 if (!rec->counter)
467                         goto again;
468         }
469
470         return rec;
471 }
472
473 static void *function_stat_start(struct tracer_stat *trace)
474 {
475         struct ftrace_profile_stat *stat =
476                 container_of(trace, struct ftrace_profile_stat, stat);
477
478         if (!stat || !stat->start)
479                 return NULL;
480
481         return function_stat_next(&stat->start->records[0], 0);
482 }
483
484 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
485 /* function graph compares on total time */
486 static int function_stat_cmp(const void *p1, const void *p2)
487 {
488         const struct ftrace_profile *a = p1;
489         const struct ftrace_profile *b = p2;
490
491         if (a->time < b->time)
492                 return -1;
493         if (a->time > b->time)
494                 return 1;
495         else
496                 return 0;
497 }
498 #else
499 /* not function graph compares against hits */
500 static int function_stat_cmp(const void *p1, const void *p2)
501 {
502         const struct ftrace_profile *a = p1;
503         const struct ftrace_profile *b = p2;
504
505         if (a->counter < b->counter)
506                 return -1;
507         if (a->counter > b->counter)
508                 return 1;
509         else
510                 return 0;
511 }
512 #endif
513
514 static int function_stat_headers(struct seq_file *m)
515 {
516 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
517         seq_puts(m, "  Function                               "
518                  "Hit    Time            Avg             s^2\n"
519                     "  --------                               "
520                  "---    ----            ---             ---\n");
521 #else
522         seq_puts(m, "  Function                               Hit\n"
523                     "  --------                               ---\n");
524 #endif
525         return 0;
526 }
527
528 static int function_stat_show(struct seq_file *m, void *v)
529 {
530         struct ftrace_profile *rec = v;
531         char str[KSYM_SYMBOL_LEN];
532         int ret = 0;
533 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
534         static struct trace_seq s;
535         unsigned long long avg;
536         unsigned long long stddev;
537 #endif
538         mutex_lock(&ftrace_profile_lock);
539
540         /* we raced with function_profile_reset() */
541         if (unlikely(rec->counter == 0)) {
542                 ret = -EBUSY;
543                 goto out;
544         }
545
546 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
547         avg = div64_ul(rec->time, rec->counter);
548         if (tracing_thresh && (avg < tracing_thresh))
549                 goto out;
550 #endif
551
552         kallsyms_lookup(rec->ip, NULL, NULL, NULL, str);
553         seq_printf(m, "  %-30.30s  %10lu", str, rec->counter);
554
555 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
556         seq_puts(m, "    ");
557
558         /* Sample standard deviation (s^2) */
559         if (rec->counter <= 1)
560                 stddev = 0;
561         else {
562                 /*
563                  * Apply Welford's method:
564                  * s^2 = 1 / (n * (n-1)) * (n * \Sum (x_i)^2 - (\Sum x_i)^2)
565                  */
566                 stddev = rec->counter * rec->time_squared -
567                          rec->time * rec->time;
568
569                 /*
570                  * Divide only 1000 for ns^2 -> us^2 conversion.
571                  * trace_print_graph_duration will divide 1000 again.
572                  */
573                 stddev = div64_ul(stddev,
574                                   rec->counter * (rec->counter - 1) * 1000);
575         }
576
577         trace_seq_init(&s);
578         trace_print_graph_duration(rec->time, &s);
579         trace_seq_puts(&s, "    ");
580         trace_print_graph_duration(avg, &s);
581         trace_seq_puts(&s, "    ");
582         trace_print_graph_duration(stddev, &s);
583         trace_print_seq(m, &s);
584 #endif
585         seq_putc(m, '\n');
586 out:
587         mutex_unlock(&ftrace_profile_lock);
588
589         return ret;
590 }
591
592 static void ftrace_profile_reset(struct ftrace_profile_stat *stat)
593 {
594         struct ftrace_profile_page *pg;
595
596         pg = stat->pages = stat->start;
597
598         while (pg) {
599                 memset(pg->records, 0, PROFILE_RECORDS_SIZE);
600                 pg->index = 0;
601                 pg = pg->next;
602         }
603
604         memset(stat->hash, 0,
605                FTRACE_PROFILE_HASH_SIZE * sizeof(struct hlist_head));
606 }
607
608 static int ftrace_profile_pages_init(struct ftrace_profile_stat *stat)
609 {
610         struct ftrace_profile_page *pg;
611         int functions;
612         int pages;
613         int i;
614
615         /* If we already allocated, do nothing */
616         if (stat->pages)
617                 return 0;
618
619         stat->pages = (void *)get_zeroed_page(GFP_KERNEL);
620         if (!stat->pages)
621                 return -ENOMEM;
622
623 #ifdef CONFIG_DYNAMIC_FTRACE
624         functions = ftrace_update_tot_cnt;
625 #else
626         /*
627          * We do not know the number of functions that exist because
628          * dynamic tracing is what counts them. With past experience
629          * we have around 20K functions. That should be more than enough.
630          * It is highly unlikely we will execute every function in
631          * the kernel.
632          */
633         functions = 20000;
634 #endif
635
636         pg = stat->start = stat->pages;
637
638         pages = DIV_ROUND_UP(functions, PROFILES_PER_PAGE);
639
640         for (i = 1; i < pages; i++) {
641                 pg->next = (void *)get_zeroed_page(GFP_KERNEL);
642                 if (!pg->next)
643                         goto out_free;
644                 pg = pg->next;
645         }
646
647         return 0;
648
649  out_free:
650         pg = stat->start;
651         while (pg) {
652                 unsigned long tmp = (unsigned long)pg;
653
654                 pg = pg->next;
655                 free_page(tmp);
656         }
657
658         stat->pages = NULL;
659         stat->start = NULL;
660
661         return -ENOMEM;
662 }
663
664 static int ftrace_profile_init_cpu(int cpu)
665 {
666         struct ftrace_profile_stat *stat;
667         int size;
668
669         stat = &per_cpu(ftrace_profile_stats, cpu);
670
671         if (stat->hash) {
672                 /* If the profile is already created, simply reset it */
673                 ftrace_profile_reset(stat);
674                 return 0;
675         }
676
677         /*
678          * We are profiling all functions, but usually only a few thousand
679          * functions are hit. We'll make a hash of 1024 items.
680          */
681         size = FTRACE_PROFILE_HASH_SIZE;
682
683         stat->hash = kcalloc(size, sizeof(struct hlist_head), GFP_KERNEL);
684
685         if (!stat->hash)
686                 return -ENOMEM;
687
688         /* Preallocate the function profiling pages */
689         if (ftrace_profile_pages_init(stat) < 0) {
690                 kfree(stat->hash);
691                 stat->hash = NULL;
692                 return -ENOMEM;
693         }
694
695         return 0;
696 }
697
698 static int ftrace_profile_init(void)
699 {
700         int cpu;
701         int ret = 0;
702
703         for_each_possible_cpu(cpu) {
704                 ret = ftrace_profile_init_cpu(cpu);
705                 if (ret)
706                         break;
707         }
708
709         return ret;
710 }
711
712 /* interrupts must be disabled */
713 static struct ftrace_profile *
714 ftrace_find_profiled_func(struct ftrace_profile_stat *stat, unsigned long ip)
715 {
716         struct ftrace_profile *rec;
717         struct hlist_head *hhd;
718         unsigned long key;
719
720         key = hash_long(ip, FTRACE_PROFILE_HASH_BITS);
721         hhd = &stat->hash[key];
722
723         if (hlist_empty(hhd))
724                 return NULL;
725
726         hlist_for_each_entry_rcu_notrace(rec, hhd, node) {
727                 if (rec->ip == ip)
728                         return rec;
729         }
730
731         return NULL;
732 }
733
734 static void ftrace_add_profile(struct ftrace_profile_stat *stat,
735                                struct ftrace_profile *rec)
736 {
737         unsigned long key;
738
739         key = hash_long(rec->ip, FTRACE_PROFILE_HASH_BITS);
740         hlist_add_head_rcu(&rec->node, &stat->hash[key]);
741 }
742
743 /*
744  * The memory is already allocated, this simply finds a new record to use.
745  */
746 static struct ftrace_profile *
747 ftrace_profile_alloc(struct ftrace_profile_stat *stat, unsigned long ip)
748 {
749         struct ftrace_profile *rec = NULL;
750
751         /* prevent recursion (from NMIs) */
752         if (atomic_inc_return(&stat->disabled) != 1)
753                 goto out;
754
755         /*
756          * Try to find the function again since an NMI
757          * could have added it
758          */
759         rec = ftrace_find_profiled_func(stat, ip);
760         if (rec)
761                 goto out;
762
763         if (stat->pages->index == PROFILES_PER_PAGE) {
764                 if (!stat->pages->next)
765                         goto out;
766                 stat->pages = stat->pages->next;
767         }
768
769         rec = &stat->pages->records[stat->pages->index++];
770         rec->ip = ip;
771         ftrace_add_profile(stat, rec);
772
773  out:
774         atomic_dec(&stat->disabled);
775
776         return rec;
777 }
778
779 static void
780 function_profile_call(unsigned long ip, unsigned long parent_ip,
781                       struct ftrace_ops *ops, struct ftrace_regs *fregs)
782 {
783         struct ftrace_profile_stat *stat;
784         struct ftrace_profile *rec;
785         unsigned long flags;
786
787         if (!ftrace_profile_enabled)
788                 return;
789
790         local_irq_save(flags);
791
792         stat = this_cpu_ptr(&ftrace_profile_stats);
793         if (!stat->hash || !ftrace_profile_enabled)
794                 goto out;
795
796         rec = ftrace_find_profiled_func(stat, ip);
797         if (!rec) {
798                 rec = ftrace_profile_alloc(stat, ip);
799                 if (!rec)
800                         goto out;
801         }
802
803         rec->counter++;
804  out:
805         local_irq_restore(flags);
806 }
807
808 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
809 static bool fgraph_graph_time = true;
810
811 void ftrace_graph_graph_time_control(bool enable)
812 {
813         fgraph_graph_time = enable;
814 }
815
816 static int profile_graph_entry(struct ftrace_graph_ent *trace)
817 {
818         struct ftrace_ret_stack *ret_stack;
819
820         function_profile_call(trace->func, 0, NULL, NULL);
821
822         /* If function graph is shutting down, ret_stack can be NULL */
823         if (!current->ret_stack)
824                 return 0;
825
826         ret_stack = ftrace_graph_get_ret_stack(current, 0);
827         if (ret_stack)
828                 ret_stack->subtime = 0;
829
830         return 1;
831 }
832
833 static void profile_graph_return(struct ftrace_graph_ret *trace)
834 {
835         struct ftrace_ret_stack *ret_stack;
836         struct ftrace_profile_stat *stat;
837         unsigned long long calltime;
838         struct ftrace_profile *rec;
839         unsigned long flags;
840
841         local_irq_save(flags);
842         stat = this_cpu_ptr(&ftrace_profile_stats);
843         if (!stat->hash || !ftrace_profile_enabled)
844                 goto out;
845
846         /* If the calltime was zero'd ignore it */
847         if (!trace->calltime)
848                 goto out;
849
850         calltime = trace->rettime - trace->calltime;
851
852         if (!fgraph_graph_time) {
853
854                 /* Append this call time to the parent time to subtract */
855                 ret_stack = ftrace_graph_get_ret_stack(current, 1);
856                 if (ret_stack)
857                         ret_stack->subtime += calltime;
858
859                 ret_stack = ftrace_graph_get_ret_stack(current, 0);
860                 if (ret_stack && ret_stack->subtime < calltime)
861                         calltime -= ret_stack->subtime;
862                 else
863                         calltime = 0;
864         }
865
866         rec = ftrace_find_profiled_func(stat, trace->func);
867         if (rec) {
868                 rec->time += calltime;
869                 rec->time_squared += calltime * calltime;
870         }
871
872  out:
873         local_irq_restore(flags);
874 }
875
876 static struct fgraph_ops fprofiler_ops = {
877         .entryfunc = &profile_graph_entry,
878         .retfunc = &profile_graph_return,
879 };
880
881 static int register_ftrace_profiler(void)
882 {
883         return register_ftrace_graph(&fprofiler_ops);
884 }
885
886 static void unregister_ftrace_profiler(void)
887 {
888         unregister_ftrace_graph(&fprofiler_ops);
889 }
890 #else
891 static struct ftrace_ops ftrace_profile_ops __read_mostly = {
892         .func           = function_profile_call,
893         .flags          = FTRACE_OPS_FL_INITIALIZED,
894         INIT_OPS_HASH(ftrace_profile_ops)
895 };
896
897 static int register_ftrace_profiler(void)
898 {
899         return register_ftrace_function(&ftrace_profile_ops);
900 }
901
902 static void unregister_ftrace_profiler(void)
903 {
904         unregister_ftrace_function(&ftrace_profile_ops);
905 }
906 #endif /* CONFIG_FUNCTION_GRAPH_TRACER */
907
908 static ssize_t
909 ftrace_profile_write(struct file *filp, const char __user *ubuf,
910                      size_t cnt, loff_t *ppos)
911 {
912         unsigned long val;
913         int ret;
914
915         ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
916         if (ret)
917                 return ret;
918
919         val = !!val;
920
921         mutex_lock(&ftrace_profile_lock);
922         if (ftrace_profile_enabled ^ val) {
923                 if (val) {
924                         ret = ftrace_profile_init();
925                         if (ret < 0) {
926                                 cnt = ret;
927                                 goto out;
928                         }
929
930                         ret = register_ftrace_profiler();
931                         if (ret < 0) {
932                                 cnt = ret;
933                                 goto out;
934                         }
935                         ftrace_profile_enabled = 1;
936                 } else {
937                         ftrace_profile_enabled = 0;
938                         /*
939                          * unregister_ftrace_profiler calls stop_machine
940                          * so this acts like an synchronize_rcu.
941                          */
942                         unregister_ftrace_profiler();
943                 }
944         }
945  out:
946         mutex_unlock(&ftrace_profile_lock);
947
948         *ppos += cnt;
949
950         return cnt;
951 }
952
953 static ssize_t
954 ftrace_profile_read(struct file *filp, char __user *ubuf,
955                      size_t cnt, loff_t *ppos)
956 {
957         char buf[64];           /* big enough to hold a number */
958         int r;
959
960         r = sprintf(buf, "%u\n", ftrace_profile_enabled);
961         return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
962 }
963
964 static const struct file_operations ftrace_profile_fops = {
965         .open           = tracing_open_generic,
966         .read           = ftrace_profile_read,
967         .write          = ftrace_profile_write,
968         .llseek         = default_llseek,
969 };
970
971 /* used to initialize the real stat files */
972 static struct tracer_stat function_stats __initdata = {
973         .name           = "functions",
974         .stat_start     = function_stat_start,
975         .stat_next      = function_stat_next,
976         .stat_cmp       = function_stat_cmp,
977         .stat_headers   = function_stat_headers,
978         .stat_show      = function_stat_show
979 };
980
981 static __init void ftrace_profile_tracefs(struct dentry *d_tracer)
982 {
983         struct ftrace_profile_stat *stat;
984         char *name;
985         int ret;
986         int cpu;
987
988         for_each_possible_cpu(cpu) {
989                 stat = &per_cpu(ftrace_profile_stats, cpu);
990
991                 name = kasprintf(GFP_KERNEL, "function%d", cpu);
992                 if (!name) {
993                         /*
994                          * The files created are permanent, if something happens
995                          * we still do not free memory.
996                          */
997                         WARN(1,
998                              "Could not allocate stat file for cpu %d\n",
999                              cpu);
1000                         return;
1001                 }
1002                 stat->stat = function_stats;
1003                 stat->stat.name = name;
1004                 ret = register_stat_tracer(&stat->stat);
1005                 if (ret) {
1006                         WARN(1,
1007                              "Could not register function stat for cpu %d\n",
1008                              cpu);
1009                         kfree(name);
1010                         return;
1011                 }
1012         }
1013
1014         trace_create_file("function_profile_enabled",
1015                           TRACE_MODE_WRITE, d_tracer, NULL,
1016                           &ftrace_profile_fops);
1017 }
1018
1019 #else /* CONFIG_FUNCTION_PROFILER */
1020 static __init void ftrace_profile_tracefs(struct dentry *d_tracer)
1021 {
1022 }
1023 #endif /* CONFIG_FUNCTION_PROFILER */
1024
1025 #ifdef CONFIG_DYNAMIC_FTRACE
1026
1027 static struct ftrace_ops *removed_ops;
1028
1029 /*
1030  * Set when doing a global update, like enabling all recs or disabling them.
1031  * It is not set when just updating a single ftrace_ops.
1032  */
1033 static bool update_all_ops;
1034
1035 #ifndef CONFIG_FTRACE_MCOUNT_RECORD
1036 # error Dynamic ftrace depends on MCOUNT_RECORD
1037 #endif
1038
1039 struct ftrace_func_probe {
1040         struct ftrace_probe_ops *probe_ops;
1041         struct ftrace_ops       ops;
1042         struct trace_array      *tr;
1043         struct list_head        list;
1044         void                    *data;
1045         int                     ref;
1046 };
1047
1048 /*
1049  * We make these constant because no one should touch them,
1050  * but they are used as the default "empty hash", to avoid allocating
1051  * it all the time. These are in a read only section such that if
1052  * anyone does try to modify it, it will cause an exception.
1053  */
1054 static const struct hlist_head empty_buckets[1];
1055 static const struct ftrace_hash empty_hash = {
1056         .buckets = (struct hlist_head *)empty_buckets,
1057 };
1058 #define EMPTY_HASH      ((struct ftrace_hash *)&empty_hash)
1059
1060 struct ftrace_ops global_ops = {
1061         .func                           = ftrace_stub,
1062         .local_hash.notrace_hash        = EMPTY_HASH,
1063         .local_hash.filter_hash         = EMPTY_HASH,
1064         INIT_OPS_HASH(global_ops)
1065         .flags                          = FTRACE_OPS_FL_INITIALIZED |
1066                                           FTRACE_OPS_FL_PID,
1067 };
1068
1069 /*
1070  * Used by the stack unwinder to know about dynamic ftrace trampolines.
1071  */
1072 struct ftrace_ops *ftrace_ops_trampoline(unsigned long addr)
1073 {
1074         struct ftrace_ops *op = NULL;
1075
1076         /*
1077          * Some of the ops may be dynamically allocated,
1078          * they are freed after a synchronize_rcu().
1079          */
1080         preempt_disable_notrace();
1081
1082         do_for_each_ftrace_op(op, ftrace_ops_list) {
1083                 /*
1084                  * This is to check for dynamically allocated trampolines.
1085                  * Trampolines that are in kernel text will have
1086                  * core_kernel_text() return true.
1087                  */
1088                 if (op->trampoline && op->trampoline_size)
1089                         if (addr >= op->trampoline &&
1090                             addr < op->trampoline + op->trampoline_size) {
1091                                 preempt_enable_notrace();
1092                                 return op;
1093                         }
1094         } while_for_each_ftrace_op(op);
1095         preempt_enable_notrace();
1096
1097         return NULL;
1098 }
1099
1100 /*
1101  * This is used by __kernel_text_address() to return true if the
1102  * address is on a dynamically allocated trampoline that would
1103  * not return true for either core_kernel_text() or
1104  * is_module_text_address().
1105  */
1106 bool is_ftrace_trampoline(unsigned long addr)
1107 {
1108         return ftrace_ops_trampoline(addr) != NULL;
1109 }
1110
1111 struct ftrace_page {
1112         struct ftrace_page      *next;
1113         struct dyn_ftrace       *records;
1114         int                     index;
1115         int                     order;
1116 };
1117
1118 #define ENTRY_SIZE sizeof(struct dyn_ftrace)
1119 #define ENTRIES_PER_PAGE (PAGE_SIZE / ENTRY_SIZE)
1120
1121 static struct ftrace_page       *ftrace_pages_start;
1122 static struct ftrace_page       *ftrace_pages;
1123
1124 static __always_inline unsigned long
1125 ftrace_hash_key(struct ftrace_hash *hash, unsigned long ip)
1126 {
1127         if (hash->size_bits > 0)
1128                 return hash_long(ip, hash->size_bits);
1129
1130         return 0;
1131 }
1132
1133 /* Only use this function if ftrace_hash_empty() has already been tested */
1134 static __always_inline struct ftrace_func_entry *
1135 __ftrace_lookup_ip(struct ftrace_hash *hash, unsigned long ip)
1136 {
1137         unsigned long key;
1138         struct ftrace_func_entry *entry;
1139         struct hlist_head *hhd;
1140
1141         key = ftrace_hash_key(hash, ip);
1142         hhd = &hash->buckets[key];
1143
1144         hlist_for_each_entry_rcu_notrace(entry, hhd, hlist) {
1145                 if (entry->ip == ip)
1146                         return entry;
1147         }
1148         return NULL;
1149 }
1150
1151 /**
1152  * ftrace_lookup_ip - Test to see if an ip exists in an ftrace_hash
1153  * @hash: The hash to look at
1154  * @ip: The instruction pointer to test
1155  *
1156  * Search a given @hash to see if a given instruction pointer (@ip)
1157  * exists in it.
1158  *
1159  * Returns the entry that holds the @ip if found. NULL otherwise.
1160  */
1161 struct ftrace_func_entry *
1162 ftrace_lookup_ip(struct ftrace_hash *hash, unsigned long ip)
1163 {
1164         if (ftrace_hash_empty(hash))
1165                 return NULL;
1166
1167         return __ftrace_lookup_ip(hash, ip);
1168 }
1169
1170 static void __add_hash_entry(struct ftrace_hash *hash,
1171                              struct ftrace_func_entry *entry)
1172 {
1173         struct hlist_head *hhd;
1174         unsigned long key;
1175
1176         key = ftrace_hash_key(hash, entry->ip);
1177         hhd = &hash->buckets[key];
1178         hlist_add_head(&entry->hlist, hhd);
1179         hash->count++;
1180 }
1181
1182 static int add_hash_entry(struct ftrace_hash *hash, unsigned long ip)
1183 {
1184         struct ftrace_func_entry *entry;
1185
1186         entry = kmalloc(sizeof(*entry), GFP_KERNEL);
1187         if (!entry)
1188                 return -ENOMEM;
1189
1190         entry->ip = ip;
1191         __add_hash_entry(hash, entry);
1192
1193         return 0;
1194 }
1195
1196 static void
1197 free_hash_entry(struct ftrace_hash *hash,
1198                   struct ftrace_func_entry *entry)
1199 {
1200         hlist_del(&entry->hlist);
1201         kfree(entry);
1202         hash->count--;
1203 }
1204
1205 static void
1206 remove_hash_entry(struct ftrace_hash *hash,
1207                   struct ftrace_func_entry *entry)
1208 {
1209         hlist_del_rcu(&entry->hlist);
1210         hash->count--;
1211 }
1212
1213 static void ftrace_hash_clear(struct ftrace_hash *hash)
1214 {
1215         struct hlist_head *hhd;
1216         struct hlist_node *tn;
1217         struct ftrace_func_entry *entry;
1218         int size = 1 << hash->size_bits;
1219         int i;
1220
1221         if (!hash->count)
1222                 return;
1223
1224         for (i = 0; i < size; i++) {
1225                 hhd = &hash->buckets[i];
1226                 hlist_for_each_entry_safe(entry, tn, hhd, hlist)
1227                         free_hash_entry(hash, entry);
1228         }
1229         FTRACE_WARN_ON(hash->count);
1230 }
1231
1232 static void free_ftrace_mod(struct ftrace_mod_load *ftrace_mod)
1233 {
1234         list_del(&ftrace_mod->list);
1235         kfree(ftrace_mod->module);
1236         kfree(ftrace_mod->func);
1237         kfree(ftrace_mod);
1238 }
1239
1240 static void clear_ftrace_mod_list(struct list_head *head)
1241 {
1242         struct ftrace_mod_load *p, *n;
1243
1244         /* stack tracer isn't supported yet */
1245         if (!head)
1246                 return;
1247
1248         mutex_lock(&ftrace_lock);
1249         list_for_each_entry_safe(p, n, head, list)
1250                 free_ftrace_mod(p);
1251         mutex_unlock(&ftrace_lock);
1252 }
1253
1254 static void free_ftrace_hash(struct ftrace_hash *hash)
1255 {
1256         if (!hash || hash == EMPTY_HASH)
1257                 return;
1258         ftrace_hash_clear(hash);
1259         kfree(hash->buckets);
1260         kfree(hash);
1261 }
1262
1263 static void __free_ftrace_hash_rcu(struct rcu_head *rcu)
1264 {
1265         struct ftrace_hash *hash;
1266
1267         hash = container_of(rcu, struct ftrace_hash, rcu);
1268         free_ftrace_hash(hash);
1269 }
1270
1271 static void free_ftrace_hash_rcu(struct ftrace_hash *hash)
1272 {
1273         if (!hash || hash == EMPTY_HASH)
1274                 return;
1275         call_rcu(&hash->rcu, __free_ftrace_hash_rcu);
1276 }
1277
1278 /**
1279  * ftrace_free_filter - remove all filters for an ftrace_ops
1280  * @ops - the ops to remove the filters from
1281  */
1282 void ftrace_free_filter(struct ftrace_ops *ops)
1283 {
1284         ftrace_ops_init(ops);
1285         free_ftrace_hash(ops->func_hash->filter_hash);
1286         free_ftrace_hash(ops->func_hash->notrace_hash);
1287 }
1288 EXPORT_SYMBOL_GPL(ftrace_free_filter);
1289
1290 static struct ftrace_hash *alloc_ftrace_hash(int size_bits)
1291 {
1292         struct ftrace_hash *hash;
1293         int size;
1294
1295         hash = kzalloc(sizeof(*hash), GFP_KERNEL);
1296         if (!hash)
1297                 return NULL;
1298
1299         size = 1 << size_bits;
1300         hash->buckets = kcalloc(size, sizeof(*hash->buckets), GFP_KERNEL);
1301
1302         if (!hash->buckets) {
1303                 kfree(hash);
1304                 return NULL;
1305         }
1306
1307         hash->size_bits = size_bits;
1308
1309         return hash;
1310 }
1311
1312
1313 static int ftrace_add_mod(struct trace_array *tr,
1314                           const char *func, const char *module,
1315                           int enable)
1316 {
1317         struct ftrace_mod_load *ftrace_mod;
1318         struct list_head *mod_head = enable ? &tr->mod_trace : &tr->mod_notrace;
1319
1320         ftrace_mod = kzalloc(sizeof(*ftrace_mod), GFP_KERNEL);
1321         if (!ftrace_mod)
1322                 return -ENOMEM;
1323
1324         INIT_LIST_HEAD(&ftrace_mod->list);
1325         ftrace_mod->func = kstrdup(func, GFP_KERNEL);
1326         ftrace_mod->module = kstrdup(module, GFP_KERNEL);
1327         ftrace_mod->enable = enable;
1328
1329         if (!ftrace_mod->func || !ftrace_mod->module)
1330                 goto out_free;
1331
1332         list_add(&ftrace_mod->list, mod_head);
1333
1334         return 0;
1335
1336  out_free:
1337         free_ftrace_mod(ftrace_mod);
1338
1339         return -ENOMEM;
1340 }
1341
1342 static struct ftrace_hash *
1343 alloc_and_copy_ftrace_hash(int size_bits, struct ftrace_hash *hash)
1344 {
1345         struct ftrace_func_entry *entry;
1346         struct ftrace_hash *new_hash;
1347         int size;
1348         int ret;
1349         int i;
1350
1351         new_hash = alloc_ftrace_hash(size_bits);
1352         if (!new_hash)
1353                 return NULL;
1354
1355         if (hash)
1356                 new_hash->flags = hash->flags;
1357
1358         /* Empty hash? */
1359         if (ftrace_hash_empty(hash))
1360                 return new_hash;
1361
1362         size = 1 << hash->size_bits;
1363         for (i = 0; i < size; i++) {
1364                 hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
1365                         ret = add_hash_entry(new_hash, entry->ip);
1366                         if (ret < 0)
1367                                 goto free_hash;
1368                 }
1369         }
1370
1371         FTRACE_WARN_ON(new_hash->count != hash->count);
1372
1373         return new_hash;
1374
1375  free_hash:
1376         free_ftrace_hash(new_hash);
1377         return NULL;
1378 }
1379
1380 static void
1381 ftrace_hash_rec_disable_modify(struct ftrace_ops *ops, int filter_hash);
1382 static void
1383 ftrace_hash_rec_enable_modify(struct ftrace_ops *ops, int filter_hash);
1384
1385 static int ftrace_hash_ipmodify_update(struct ftrace_ops *ops,
1386                                        struct ftrace_hash *new_hash);
1387
1388 static struct ftrace_hash *dup_hash(struct ftrace_hash *src, int size)
1389 {
1390         struct ftrace_func_entry *entry;
1391         struct ftrace_hash *new_hash;
1392         struct hlist_head *hhd;
1393         struct hlist_node *tn;
1394         int bits = 0;
1395         int i;
1396
1397         /*
1398          * Use around half the size (max bit of it), but
1399          * a minimum of 2 is fine (as size of 0 or 1 both give 1 for bits).
1400          */
1401         bits = fls(size / 2);
1402
1403         /* Don't allocate too much */
1404         if (bits > FTRACE_HASH_MAX_BITS)
1405                 bits = FTRACE_HASH_MAX_BITS;
1406
1407         new_hash = alloc_ftrace_hash(bits);
1408         if (!new_hash)
1409                 return NULL;
1410
1411         new_hash->flags = src->flags;
1412
1413         size = 1 << src->size_bits;
1414         for (i = 0; i < size; i++) {
1415                 hhd = &src->buckets[i];
1416                 hlist_for_each_entry_safe(entry, tn, hhd, hlist) {
1417                         remove_hash_entry(src, entry);
1418                         __add_hash_entry(new_hash, entry);
1419                 }
1420         }
1421         return new_hash;
1422 }
1423
1424 static struct ftrace_hash *
1425 __ftrace_hash_move(struct ftrace_hash *src)
1426 {
1427         int size = src->count;
1428
1429         /*
1430          * If the new source is empty, just return the empty_hash.
1431          */
1432         if (ftrace_hash_empty(src))
1433                 return EMPTY_HASH;
1434
1435         return dup_hash(src, size);
1436 }
1437
1438 static int
1439 ftrace_hash_move(struct ftrace_ops *ops, int enable,
1440                  struct ftrace_hash **dst, struct ftrace_hash *src)
1441 {
1442         struct ftrace_hash *new_hash;
1443         int ret;
1444
1445         /* Reject setting notrace hash on IPMODIFY ftrace_ops */
1446         if (ops->flags & FTRACE_OPS_FL_IPMODIFY && !enable)
1447                 return -EINVAL;
1448
1449         new_hash = __ftrace_hash_move(src);
1450         if (!new_hash)
1451                 return -ENOMEM;
1452
1453         /* Make sure this can be applied if it is IPMODIFY ftrace_ops */
1454         if (enable) {
1455                 /* IPMODIFY should be updated only when filter_hash updating */
1456                 ret = ftrace_hash_ipmodify_update(ops, new_hash);
1457                 if (ret < 0) {
1458                         free_ftrace_hash(new_hash);
1459                         return ret;
1460                 }
1461         }
1462
1463         /*
1464          * Remove the current set, update the hash and add
1465          * them back.
1466          */
1467         ftrace_hash_rec_disable_modify(ops, enable);
1468
1469         rcu_assign_pointer(*dst, new_hash);
1470
1471         ftrace_hash_rec_enable_modify(ops, enable);
1472
1473         return 0;
1474 }
1475
1476 static bool hash_contains_ip(unsigned long ip,
1477                              struct ftrace_ops_hash *hash)
1478 {
1479         /*
1480          * The function record is a match if it exists in the filter
1481          * hash and not in the notrace hash. Note, an empty hash is
1482          * considered a match for the filter hash, but an empty
1483          * notrace hash is considered not in the notrace hash.
1484          */
1485         return (ftrace_hash_empty(hash->filter_hash) ||
1486                 __ftrace_lookup_ip(hash->filter_hash, ip)) &&
1487                 (ftrace_hash_empty(hash->notrace_hash) ||
1488                  !__ftrace_lookup_ip(hash->notrace_hash, ip));
1489 }
1490
1491 /*
1492  * Test the hashes for this ops to see if we want to call
1493  * the ops->func or not.
1494  *
1495  * It's a match if the ip is in the ops->filter_hash or
1496  * the filter_hash does not exist or is empty,
1497  *  AND
1498  * the ip is not in the ops->notrace_hash.
1499  *
1500  * This needs to be called with preemption disabled as
1501  * the hashes are freed with call_rcu().
1502  */
1503 int
1504 ftrace_ops_test(struct ftrace_ops *ops, unsigned long ip, void *regs)
1505 {
1506         struct ftrace_ops_hash hash;
1507         int ret;
1508
1509 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_REGS
1510         /*
1511          * There's a small race when adding ops that the ftrace handler
1512          * that wants regs, may be called without them. We can not
1513          * allow that handler to be called if regs is NULL.
1514          */
1515         if (regs == NULL && (ops->flags & FTRACE_OPS_FL_SAVE_REGS))
1516                 return 0;
1517 #endif
1518
1519         rcu_assign_pointer(hash.filter_hash, ops->func_hash->filter_hash);
1520         rcu_assign_pointer(hash.notrace_hash, ops->func_hash->notrace_hash);
1521
1522         if (hash_contains_ip(ip, &hash))
1523                 ret = 1;
1524         else
1525                 ret = 0;
1526
1527         return ret;
1528 }
1529
1530 /*
1531  * This is a double for. Do not use 'break' to break out of the loop,
1532  * you must use a goto.
1533  */
1534 #define do_for_each_ftrace_rec(pg, rec)                                 \
1535         for (pg = ftrace_pages_start; pg; pg = pg->next) {              \
1536                 int _____i;                                             \
1537                 for (_____i = 0; _____i < pg->index; _____i++) {        \
1538                         rec = &pg->records[_____i];
1539
1540 #define while_for_each_ftrace_rec()             \
1541                 }                               \
1542         }
1543
1544
1545 static int ftrace_cmp_recs(const void *a, const void *b)
1546 {
1547         const struct dyn_ftrace *key = a;
1548         const struct dyn_ftrace *rec = b;
1549
1550         if (key->flags < rec->ip)
1551                 return -1;
1552         if (key->ip >= rec->ip + MCOUNT_INSN_SIZE)
1553                 return 1;
1554         return 0;
1555 }
1556
1557 static struct dyn_ftrace *lookup_rec(unsigned long start, unsigned long end)
1558 {
1559         struct ftrace_page *pg;
1560         struct dyn_ftrace *rec = NULL;
1561         struct dyn_ftrace key;
1562
1563         key.ip = start;
1564         key.flags = end;        /* overload flags, as it is unsigned long */
1565
1566         for (pg = ftrace_pages_start; pg; pg = pg->next) {
1567                 if (pg->index == 0 ||
1568                     end < pg->records[0].ip ||
1569                     start >= (pg->records[pg->index - 1].ip + MCOUNT_INSN_SIZE))
1570                         continue;
1571                 rec = bsearch(&key, pg->records, pg->index,
1572                               sizeof(struct dyn_ftrace),
1573                               ftrace_cmp_recs);
1574                 if (rec)
1575                         break;
1576         }
1577         return rec;
1578 }
1579
1580 /**
1581  * ftrace_location_range - return the first address of a traced location
1582  *      if it touches the given ip range
1583  * @start: start of range to search.
1584  * @end: end of range to search (inclusive). @end points to the last byte
1585  *      to check.
1586  *
1587  * Returns rec->ip if the related ftrace location is a least partly within
1588  * the given address range. That is, the first address of the instruction
1589  * that is either a NOP or call to the function tracer. It checks the ftrace
1590  * internal tables to determine if the address belongs or not.
1591  */
1592 unsigned long ftrace_location_range(unsigned long start, unsigned long end)
1593 {
1594         struct dyn_ftrace *rec;
1595
1596         rec = lookup_rec(start, end);
1597         if (rec)
1598                 return rec->ip;
1599
1600         return 0;
1601 }
1602
1603 /**
1604  * ftrace_location - return the ftrace location
1605  * @ip: the instruction pointer to check
1606  *
1607  * If @ip matches the ftrace location, return @ip.
1608  * If @ip matches sym+0, return sym's ftrace location.
1609  * Otherwise, return 0.
1610  */
1611 unsigned long ftrace_location(unsigned long ip)
1612 {
1613         struct dyn_ftrace *rec;
1614         unsigned long offset;
1615         unsigned long size;
1616
1617         rec = lookup_rec(ip, ip);
1618         if (!rec) {
1619                 if (!kallsyms_lookup_size_offset(ip, &size, &offset))
1620                         goto out;
1621
1622                 /* map sym+0 to __fentry__ */
1623                 if (!offset)
1624                         rec = lookup_rec(ip, ip + size - 1);
1625         }
1626
1627         if (rec)
1628                 return rec->ip;
1629
1630 out:
1631         return 0;
1632 }
1633
1634 /**
1635  * ftrace_text_reserved - return true if range contains an ftrace location
1636  * @start: start of range to search
1637  * @end: end of range to search (inclusive). @end points to the last byte to check.
1638  *
1639  * Returns 1 if @start and @end contains a ftrace location.
1640  * That is, the instruction that is either a NOP or call to
1641  * the function tracer. It checks the ftrace internal tables to
1642  * determine if the address belongs or not.
1643  */
1644 int ftrace_text_reserved(const void *start, const void *end)
1645 {
1646         unsigned long ret;
1647
1648         ret = ftrace_location_range((unsigned long)start,
1649                                     (unsigned long)end);
1650
1651         return (int)!!ret;
1652 }
1653
1654 /* Test if ops registered to this rec needs regs */
1655 static bool test_rec_ops_needs_regs(struct dyn_ftrace *rec)
1656 {
1657         struct ftrace_ops *ops;
1658         bool keep_regs = false;
1659
1660         for (ops = ftrace_ops_list;
1661              ops != &ftrace_list_end; ops = ops->next) {
1662                 /* pass rec in as regs to have non-NULL val */
1663                 if (ftrace_ops_test(ops, rec->ip, rec)) {
1664                         if (ops->flags & FTRACE_OPS_FL_SAVE_REGS) {
1665                                 keep_regs = true;
1666                                 break;
1667                         }
1668                 }
1669         }
1670
1671         return  keep_regs;
1672 }
1673
1674 static struct ftrace_ops *
1675 ftrace_find_tramp_ops_any(struct dyn_ftrace *rec);
1676 static struct ftrace_ops *
1677 ftrace_find_tramp_ops_any_other(struct dyn_ftrace *rec, struct ftrace_ops *op_exclude);
1678 static struct ftrace_ops *
1679 ftrace_find_tramp_ops_next(struct dyn_ftrace *rec, struct ftrace_ops *ops);
1680
1681 static bool skip_record(struct dyn_ftrace *rec)
1682 {
1683         /*
1684          * At boot up, weak functions are set to disable. Function tracing
1685          * can be enabled before they are, and they still need to be disabled now.
1686          * If the record is disabled, still continue if it is marked as already
1687          * enabled (this is needed to keep the accounting working).
1688          */
1689         return rec->flags & FTRACE_FL_DISABLED &&
1690                 !(rec->flags & FTRACE_FL_ENABLED);
1691 }
1692
1693 static bool __ftrace_hash_rec_update(struct ftrace_ops *ops,
1694                                      int filter_hash,
1695                                      bool inc)
1696 {
1697         struct ftrace_hash *hash;
1698         struct ftrace_hash *other_hash;
1699         struct ftrace_page *pg;
1700         struct dyn_ftrace *rec;
1701         bool update = false;
1702         int count = 0;
1703         int all = false;
1704
1705         /* Only update if the ops has been registered */
1706         if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
1707                 return false;
1708
1709         /*
1710          * In the filter_hash case:
1711          *   If the count is zero, we update all records.
1712          *   Otherwise we just update the items in the hash.
1713          *
1714          * In the notrace_hash case:
1715          *   We enable the update in the hash.
1716          *   As disabling notrace means enabling the tracing,
1717          *   and enabling notrace means disabling, the inc variable
1718          *   gets inversed.
1719          */
1720         if (filter_hash) {
1721                 hash = ops->func_hash->filter_hash;
1722                 other_hash = ops->func_hash->notrace_hash;
1723                 if (ftrace_hash_empty(hash))
1724                         all = true;
1725         } else {
1726                 inc = !inc;
1727                 hash = ops->func_hash->notrace_hash;
1728                 other_hash = ops->func_hash->filter_hash;
1729                 /*
1730                  * If the notrace hash has no items,
1731                  * then there's nothing to do.
1732                  */
1733                 if (ftrace_hash_empty(hash))
1734                         return false;
1735         }
1736
1737         do_for_each_ftrace_rec(pg, rec) {
1738                 int in_other_hash = 0;
1739                 int in_hash = 0;
1740                 int match = 0;
1741
1742                 if (skip_record(rec))
1743                         continue;
1744
1745                 if (all) {
1746                         /*
1747                          * Only the filter_hash affects all records.
1748                          * Update if the record is not in the notrace hash.
1749                          */
1750                         if (!other_hash || !ftrace_lookup_ip(other_hash, rec->ip))
1751                                 match = 1;
1752                 } else {
1753                         in_hash = !!ftrace_lookup_ip(hash, rec->ip);
1754                         in_other_hash = !!ftrace_lookup_ip(other_hash, rec->ip);
1755
1756                         /*
1757                          * If filter_hash is set, we want to match all functions
1758                          * that are in the hash but not in the other hash.
1759                          *
1760                          * If filter_hash is not set, then we are decrementing.
1761                          * That means we match anything that is in the hash
1762                          * and also in the other_hash. That is, we need to turn
1763                          * off functions in the other hash because they are disabled
1764                          * by this hash.
1765                          */
1766                         if (filter_hash && in_hash && !in_other_hash)
1767                                 match = 1;
1768                         else if (!filter_hash && in_hash &&
1769                                  (in_other_hash || ftrace_hash_empty(other_hash)))
1770                                 match = 1;
1771                 }
1772                 if (!match)
1773                         continue;
1774
1775                 if (inc) {
1776                         rec->flags++;
1777                         if (FTRACE_WARN_ON(ftrace_rec_count(rec) == FTRACE_REF_MAX))
1778                                 return false;
1779
1780                         if (ops->flags & FTRACE_OPS_FL_DIRECT)
1781                                 rec->flags |= FTRACE_FL_DIRECT;
1782
1783                         /*
1784                          * If there's only a single callback registered to a
1785                          * function, and the ops has a trampoline registered
1786                          * for it, then we can call it directly.
1787                          */
1788                         if (ftrace_rec_count(rec) == 1 && ops->trampoline)
1789                                 rec->flags |= FTRACE_FL_TRAMP;
1790                         else
1791                                 /*
1792                                  * If we are adding another function callback
1793                                  * to this function, and the previous had a
1794                                  * custom trampoline in use, then we need to go
1795                                  * back to the default trampoline.
1796                                  */
1797                                 rec->flags &= ~FTRACE_FL_TRAMP;
1798
1799                         /*
1800                          * If any ops wants regs saved for this function
1801                          * then all ops will get saved regs.
1802                          */
1803                         if (ops->flags & FTRACE_OPS_FL_SAVE_REGS)
1804                                 rec->flags |= FTRACE_FL_REGS;
1805                 } else {
1806                         if (FTRACE_WARN_ON(ftrace_rec_count(rec) == 0))
1807                                 return false;
1808                         rec->flags--;
1809
1810                         /*
1811                          * Only the internal direct_ops should have the
1812                          * DIRECT flag set. Thus, if it is removing a
1813                          * function, then that function should no longer
1814                          * be direct.
1815                          */
1816                         if (ops->flags & FTRACE_OPS_FL_DIRECT)
1817                                 rec->flags &= ~FTRACE_FL_DIRECT;
1818
1819                         /*
1820                          * If the rec had REGS enabled and the ops that is
1821                          * being removed had REGS set, then see if there is
1822                          * still any ops for this record that wants regs.
1823                          * If not, we can stop recording them.
1824                          */
1825                         if (ftrace_rec_count(rec) > 0 &&
1826                             rec->flags & FTRACE_FL_REGS &&
1827                             ops->flags & FTRACE_OPS_FL_SAVE_REGS) {
1828                                 if (!test_rec_ops_needs_regs(rec))
1829                                         rec->flags &= ~FTRACE_FL_REGS;
1830                         }
1831
1832                         /*
1833                          * The TRAMP needs to be set only if rec count
1834                          * is decremented to one, and the ops that is
1835                          * left has a trampoline. As TRAMP can only be
1836                          * enabled if there is only a single ops attached
1837                          * to it.
1838                          */
1839                         if (ftrace_rec_count(rec) == 1 &&
1840                             ftrace_find_tramp_ops_any_other(rec, ops))
1841                                 rec->flags |= FTRACE_FL_TRAMP;
1842                         else
1843                                 rec->flags &= ~FTRACE_FL_TRAMP;
1844
1845                         /*
1846                          * flags will be cleared in ftrace_check_record()
1847                          * if rec count is zero.
1848                          */
1849                 }
1850
1851                 /*
1852                  * If the rec has a single associated ops, and ops->func can be
1853                  * called directly, allow the call site to call via the ops.
1854                  */
1855                 if (IS_ENABLED(CONFIG_DYNAMIC_FTRACE_WITH_CALL_OPS) &&
1856                     ftrace_rec_count(rec) == 1 &&
1857                     ftrace_ops_get_func(ops) == ops->func)
1858                         rec->flags |= FTRACE_FL_CALL_OPS;
1859                 else
1860                         rec->flags &= ~FTRACE_FL_CALL_OPS;
1861
1862                 count++;
1863
1864                 /* Must match FTRACE_UPDATE_CALLS in ftrace_modify_all_code() */
1865                 update |= ftrace_test_record(rec, true) != FTRACE_UPDATE_IGNORE;
1866
1867                 /* Shortcut, if we handled all records, we are done. */
1868                 if (!all && count == hash->count)
1869                         return update;
1870         } while_for_each_ftrace_rec();
1871
1872         return update;
1873 }
1874
1875 static bool ftrace_hash_rec_disable(struct ftrace_ops *ops,
1876                                     int filter_hash)
1877 {
1878         return __ftrace_hash_rec_update(ops, filter_hash, 0);
1879 }
1880
1881 static bool ftrace_hash_rec_enable(struct ftrace_ops *ops,
1882                                    int filter_hash)
1883 {
1884         return __ftrace_hash_rec_update(ops, filter_hash, 1);
1885 }
1886
1887 static void ftrace_hash_rec_update_modify(struct ftrace_ops *ops,
1888                                           int filter_hash, int inc)
1889 {
1890         struct ftrace_ops *op;
1891
1892         __ftrace_hash_rec_update(ops, filter_hash, inc);
1893
1894         if (ops->func_hash != &global_ops.local_hash)
1895                 return;
1896
1897         /*
1898          * If the ops shares the global_ops hash, then we need to update
1899          * all ops that are enabled and use this hash.
1900          */
1901         do_for_each_ftrace_op(op, ftrace_ops_list) {
1902                 /* Already done */
1903                 if (op == ops)
1904                         continue;
1905                 if (op->func_hash == &global_ops.local_hash)
1906                         __ftrace_hash_rec_update(op, filter_hash, inc);
1907         } while_for_each_ftrace_op(op);
1908 }
1909
1910 static void ftrace_hash_rec_disable_modify(struct ftrace_ops *ops,
1911                                            int filter_hash)
1912 {
1913         ftrace_hash_rec_update_modify(ops, filter_hash, 0);
1914 }
1915
1916 static void ftrace_hash_rec_enable_modify(struct ftrace_ops *ops,
1917                                           int filter_hash)
1918 {
1919         ftrace_hash_rec_update_modify(ops, filter_hash, 1);
1920 }
1921
1922 /*
1923  * Try to update IPMODIFY flag on each ftrace_rec. Return 0 if it is OK
1924  * or no-needed to update, -EBUSY if it detects a conflict of the flag
1925  * on a ftrace_rec, and -EINVAL if the new_hash tries to trace all recs.
1926  * Note that old_hash and new_hash has below meanings
1927  *  - If the hash is NULL, it hits all recs (if IPMODIFY is set, this is rejected)
1928  *  - If the hash is EMPTY_HASH, it hits nothing
1929  *  - Anything else hits the recs which match the hash entries.
1930  *
1931  * DIRECT ops does not have IPMODIFY flag, but we still need to check it
1932  * against functions with FTRACE_FL_IPMODIFY. If there is any overlap, call
1933  * ops_func(SHARE_IPMODIFY_SELF) to make sure current ops can share with
1934  * IPMODIFY. If ops_func(SHARE_IPMODIFY_SELF) returns non-zero, propagate
1935  * the return value to the caller and eventually to the owner of the DIRECT
1936  * ops.
1937  */
1938 static int __ftrace_hash_update_ipmodify(struct ftrace_ops *ops,
1939                                          struct ftrace_hash *old_hash,
1940                                          struct ftrace_hash *new_hash)
1941 {
1942         struct ftrace_page *pg;
1943         struct dyn_ftrace *rec, *end = NULL;
1944         int in_old, in_new;
1945         bool is_ipmodify, is_direct;
1946
1947         /* Only update if the ops has been registered */
1948         if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
1949                 return 0;
1950
1951         is_ipmodify = ops->flags & FTRACE_OPS_FL_IPMODIFY;
1952         is_direct = ops->flags & FTRACE_OPS_FL_DIRECT;
1953
1954         /* neither IPMODIFY nor DIRECT, skip */
1955         if (!is_ipmodify && !is_direct)
1956                 return 0;
1957
1958         if (WARN_ON_ONCE(is_ipmodify && is_direct))
1959                 return 0;
1960
1961         /*
1962          * Since the IPMODIFY and DIRECT are very address sensitive
1963          * actions, we do not allow ftrace_ops to set all functions to new
1964          * hash.
1965          */
1966         if (!new_hash || !old_hash)
1967                 return -EINVAL;
1968
1969         /* Update rec->flags */
1970         do_for_each_ftrace_rec(pg, rec) {
1971
1972                 if (rec->flags & FTRACE_FL_DISABLED)
1973                         continue;
1974
1975                 /* We need to update only differences of filter_hash */
1976                 in_old = !!ftrace_lookup_ip(old_hash, rec->ip);
1977                 in_new = !!ftrace_lookup_ip(new_hash, rec->ip);
1978                 if (in_old == in_new)
1979                         continue;
1980
1981                 if (in_new) {
1982                         if (rec->flags & FTRACE_FL_IPMODIFY) {
1983                                 int ret;
1984
1985                                 /* Cannot have two ipmodify on same rec */
1986                                 if (is_ipmodify)
1987                                         goto rollback;
1988
1989                                 FTRACE_WARN_ON(rec->flags & FTRACE_FL_DIRECT);
1990
1991                                 /*
1992                                  * Another ops with IPMODIFY is already
1993                                  * attached. We are now attaching a direct
1994                                  * ops. Run SHARE_IPMODIFY_SELF, to check
1995                                  * whether sharing is supported.
1996                                  */
1997                                 if (!ops->ops_func)
1998                                         return -EBUSY;
1999                                 ret = ops->ops_func(ops, FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_SELF);
2000                                 if (ret)
2001                                         return ret;
2002                         } else if (is_ipmodify) {
2003                                 rec->flags |= FTRACE_FL_IPMODIFY;
2004                         }
2005                 } else if (is_ipmodify) {
2006                         rec->flags &= ~FTRACE_FL_IPMODIFY;
2007                 }
2008         } while_for_each_ftrace_rec();
2009
2010         return 0;
2011
2012 rollback:
2013         end = rec;
2014
2015         /* Roll back what we did above */
2016         do_for_each_ftrace_rec(pg, rec) {
2017
2018                 if (rec->flags & FTRACE_FL_DISABLED)
2019                         continue;
2020
2021                 if (rec == end)
2022                         goto err_out;
2023
2024                 in_old = !!ftrace_lookup_ip(old_hash, rec->ip);
2025                 in_new = !!ftrace_lookup_ip(new_hash, rec->ip);
2026                 if (in_old == in_new)
2027                         continue;
2028
2029                 if (in_new)
2030                         rec->flags &= ~FTRACE_FL_IPMODIFY;
2031                 else
2032                         rec->flags |= FTRACE_FL_IPMODIFY;
2033         } while_for_each_ftrace_rec();
2034
2035 err_out:
2036         return -EBUSY;
2037 }
2038
2039 static int ftrace_hash_ipmodify_enable(struct ftrace_ops *ops)
2040 {
2041         struct ftrace_hash *hash = ops->func_hash->filter_hash;
2042
2043         if (ftrace_hash_empty(hash))
2044                 hash = NULL;
2045
2046         return __ftrace_hash_update_ipmodify(ops, EMPTY_HASH, hash);
2047 }
2048
2049 /* Disabling always succeeds */
2050 static void ftrace_hash_ipmodify_disable(struct ftrace_ops *ops)
2051 {
2052         struct ftrace_hash *hash = ops->func_hash->filter_hash;
2053
2054         if (ftrace_hash_empty(hash))
2055                 hash = NULL;
2056
2057         __ftrace_hash_update_ipmodify(ops, hash, EMPTY_HASH);
2058 }
2059
2060 static int ftrace_hash_ipmodify_update(struct ftrace_ops *ops,
2061                                        struct ftrace_hash *new_hash)
2062 {
2063         struct ftrace_hash *old_hash = ops->func_hash->filter_hash;
2064
2065         if (ftrace_hash_empty(old_hash))
2066                 old_hash = NULL;
2067
2068         if (ftrace_hash_empty(new_hash))
2069                 new_hash = NULL;
2070
2071         return __ftrace_hash_update_ipmodify(ops, old_hash, new_hash);
2072 }
2073
2074 static void print_ip_ins(const char *fmt, const unsigned char *p)
2075 {
2076         char ins[MCOUNT_INSN_SIZE];
2077
2078         if (copy_from_kernel_nofault(ins, p, MCOUNT_INSN_SIZE)) {
2079                 printk(KERN_CONT "%s[FAULT] %px\n", fmt, p);
2080                 return;
2081         }
2082
2083         printk(KERN_CONT "%s", fmt);
2084         pr_cont("%*phC", MCOUNT_INSN_SIZE, ins);
2085 }
2086
2087 enum ftrace_bug_type ftrace_bug_type;
2088 const void *ftrace_expected;
2089
2090 static void print_bug_type(void)
2091 {
2092         switch (ftrace_bug_type) {
2093         case FTRACE_BUG_UNKNOWN:
2094                 break;
2095         case FTRACE_BUG_INIT:
2096                 pr_info("Initializing ftrace call sites\n");
2097                 break;
2098         case FTRACE_BUG_NOP:
2099                 pr_info("Setting ftrace call site to NOP\n");
2100                 break;
2101         case FTRACE_BUG_CALL:
2102                 pr_info("Setting ftrace call site to call ftrace function\n");
2103                 break;
2104         case FTRACE_BUG_UPDATE:
2105                 pr_info("Updating ftrace call site to call a different ftrace function\n");
2106                 break;
2107         }
2108 }
2109
2110 /**
2111  * ftrace_bug - report and shutdown function tracer
2112  * @failed: The failed type (EFAULT, EINVAL, EPERM)
2113  * @rec: The record that failed
2114  *
2115  * The arch code that enables or disables the function tracing
2116  * can call ftrace_bug() when it has detected a problem in
2117  * modifying the code. @failed should be one of either:
2118  * EFAULT - if the problem happens on reading the @ip address
2119  * EINVAL - if what is read at @ip is not what was expected
2120  * EPERM - if the problem happens on writing to the @ip address
2121  */
2122 void ftrace_bug(int failed, struct dyn_ftrace *rec)
2123 {
2124         unsigned long ip = rec ? rec->ip : 0;
2125
2126         pr_info("------------[ ftrace bug ]------------\n");
2127
2128         switch (failed) {
2129         case -EFAULT:
2130                 pr_info("ftrace faulted on modifying ");
2131                 print_ip_sym(KERN_INFO, ip);
2132                 break;
2133         case -EINVAL:
2134                 pr_info("ftrace failed to modify ");
2135                 print_ip_sym(KERN_INFO, ip);
2136                 print_ip_ins(" actual:   ", (unsigned char *)ip);
2137                 pr_cont("\n");
2138                 if (ftrace_expected) {
2139                         print_ip_ins(" expected: ", ftrace_expected);
2140                         pr_cont("\n");
2141                 }
2142                 break;
2143         case -EPERM:
2144                 pr_info("ftrace faulted on writing ");
2145                 print_ip_sym(KERN_INFO, ip);
2146                 break;
2147         default:
2148                 pr_info("ftrace faulted on unknown error ");
2149                 print_ip_sym(KERN_INFO, ip);
2150         }
2151         print_bug_type();
2152         if (rec) {
2153                 struct ftrace_ops *ops = NULL;
2154
2155                 pr_info("ftrace record flags: %lx\n", rec->flags);
2156                 pr_cont(" (%ld)%s%s", ftrace_rec_count(rec),
2157                         rec->flags & FTRACE_FL_REGS ? " R" : "  ",
2158                         rec->flags & FTRACE_FL_CALL_OPS ? " O" : "  ");
2159                 if (rec->flags & FTRACE_FL_TRAMP_EN) {
2160                         ops = ftrace_find_tramp_ops_any(rec);
2161                         if (ops) {
2162                                 do {
2163                                         pr_cont("\ttramp: %pS (%pS)",
2164                                                 (void *)ops->trampoline,
2165                                                 (void *)ops->func);
2166                                         ops = ftrace_find_tramp_ops_next(rec, ops);
2167                                 } while (ops);
2168                         } else
2169                                 pr_cont("\ttramp: ERROR!");
2170
2171                 }
2172                 ip = ftrace_get_addr_curr(rec);
2173                 pr_cont("\n expected tramp: %lx\n", ip);
2174         }
2175
2176         FTRACE_WARN_ON_ONCE(1);
2177 }
2178
2179 static int ftrace_check_record(struct dyn_ftrace *rec, bool enable, bool update)
2180 {
2181         unsigned long flag = 0UL;
2182
2183         ftrace_bug_type = FTRACE_BUG_UNKNOWN;
2184
2185         if (skip_record(rec))
2186                 return FTRACE_UPDATE_IGNORE;
2187
2188         /*
2189          * If we are updating calls:
2190          *
2191          *   If the record has a ref count, then we need to enable it
2192          *   because someone is using it.
2193          *
2194          *   Otherwise we make sure its disabled.
2195          *
2196          * If we are disabling calls, then disable all records that
2197          * are enabled.
2198          */
2199         if (enable && ftrace_rec_count(rec))
2200                 flag = FTRACE_FL_ENABLED;
2201
2202         /*
2203          * If enabling and the REGS flag does not match the REGS_EN, or
2204          * the TRAMP flag doesn't match the TRAMP_EN, then do not ignore
2205          * this record. Set flags to fail the compare against ENABLED.
2206          * Same for direct calls.
2207          */
2208         if (flag) {
2209                 if (!(rec->flags & FTRACE_FL_REGS) !=
2210                     !(rec->flags & FTRACE_FL_REGS_EN))
2211                         flag |= FTRACE_FL_REGS;
2212
2213                 if (!(rec->flags & FTRACE_FL_TRAMP) !=
2214                     !(rec->flags & FTRACE_FL_TRAMP_EN))
2215                         flag |= FTRACE_FL_TRAMP;
2216
2217                 /*
2218                  * Direct calls are special, as count matters.
2219                  * We must test the record for direct, if the
2220                  * DIRECT and DIRECT_EN do not match, but only
2221                  * if the count is 1. That's because, if the
2222                  * count is something other than one, we do not
2223                  * want the direct enabled (it will be done via the
2224                  * direct helper). But if DIRECT_EN is set, and
2225                  * the count is not one, we need to clear it.
2226                  *
2227                  */
2228                 if (ftrace_rec_count(rec) == 1) {
2229                         if (!(rec->flags & FTRACE_FL_DIRECT) !=
2230                             !(rec->flags & FTRACE_FL_DIRECT_EN))
2231                                 flag |= FTRACE_FL_DIRECT;
2232                 } else if (rec->flags & FTRACE_FL_DIRECT_EN) {
2233                         flag |= FTRACE_FL_DIRECT;
2234                 }
2235
2236                 /*
2237                  * Ops calls are special, as count matters.
2238                  * As with direct calls, they must only be enabled when count
2239                  * is one, otherwise they'll be handled via the list ops.
2240                  */
2241                 if (ftrace_rec_count(rec) == 1) {
2242                         if (!(rec->flags & FTRACE_FL_CALL_OPS) !=
2243                             !(rec->flags & FTRACE_FL_CALL_OPS_EN))
2244                                 flag |= FTRACE_FL_CALL_OPS;
2245                 } else if (rec->flags & FTRACE_FL_CALL_OPS_EN) {
2246                         flag |= FTRACE_FL_CALL_OPS;
2247                 }
2248         }
2249
2250         /* If the state of this record hasn't changed, then do nothing */
2251         if ((rec->flags & FTRACE_FL_ENABLED) == flag)
2252                 return FTRACE_UPDATE_IGNORE;
2253
2254         if (flag) {
2255                 /* Save off if rec is being enabled (for return value) */
2256                 flag ^= rec->flags & FTRACE_FL_ENABLED;
2257
2258                 if (update) {
2259                         rec->flags |= FTRACE_FL_ENABLED;
2260                         if (flag & FTRACE_FL_REGS) {
2261                                 if (rec->flags & FTRACE_FL_REGS)
2262                                         rec->flags |= FTRACE_FL_REGS_EN;
2263                                 else
2264                                         rec->flags &= ~FTRACE_FL_REGS_EN;
2265                         }
2266                         if (flag & FTRACE_FL_TRAMP) {
2267                                 if (rec->flags & FTRACE_FL_TRAMP)
2268                                         rec->flags |= FTRACE_FL_TRAMP_EN;
2269                                 else
2270                                         rec->flags &= ~FTRACE_FL_TRAMP_EN;
2271                         }
2272
2273                         if (flag & FTRACE_FL_DIRECT) {
2274                                 /*
2275                                  * If there's only one user (direct_ops helper)
2276                                  * then we can call the direct function
2277                                  * directly (no ftrace trampoline).
2278                                  */
2279                                 if (ftrace_rec_count(rec) == 1) {
2280                                         if (rec->flags & FTRACE_FL_DIRECT)
2281                                                 rec->flags |= FTRACE_FL_DIRECT_EN;
2282                                         else
2283                                                 rec->flags &= ~FTRACE_FL_DIRECT_EN;
2284                                 } else {
2285                                         /*
2286                                          * Can only call directly if there's
2287                                          * only one callback to the function.
2288                                          */
2289                                         rec->flags &= ~FTRACE_FL_DIRECT_EN;
2290                                 }
2291                         }
2292
2293                         if (flag & FTRACE_FL_CALL_OPS) {
2294                                 if (ftrace_rec_count(rec) == 1) {
2295                                         if (rec->flags & FTRACE_FL_CALL_OPS)
2296                                                 rec->flags |= FTRACE_FL_CALL_OPS_EN;
2297                                         else
2298                                                 rec->flags &= ~FTRACE_FL_CALL_OPS_EN;
2299                                 } else {
2300                                         /*
2301                                          * Can only call directly if there's
2302                                          * only one set of associated ops.
2303                                          */
2304                                         rec->flags &= ~FTRACE_FL_CALL_OPS_EN;
2305                                 }
2306                         }
2307                 }
2308
2309                 /*
2310                  * If this record is being updated from a nop, then
2311                  *   return UPDATE_MAKE_CALL.
2312                  * Otherwise,
2313                  *   return UPDATE_MODIFY_CALL to tell the caller to convert
2314                  *   from the save regs, to a non-save regs function or
2315                  *   vice versa, or from a trampoline call.
2316                  */
2317                 if (flag & FTRACE_FL_ENABLED) {
2318                         ftrace_bug_type = FTRACE_BUG_CALL;
2319                         return FTRACE_UPDATE_MAKE_CALL;
2320                 }
2321
2322                 ftrace_bug_type = FTRACE_BUG_UPDATE;
2323                 return FTRACE_UPDATE_MODIFY_CALL;
2324         }
2325
2326         if (update) {
2327                 /* If there's no more users, clear all flags */
2328                 if (!ftrace_rec_count(rec))
2329                         rec->flags &= FTRACE_FL_DISABLED;
2330                 else
2331                         /*
2332                          * Just disable the record, but keep the ops TRAMP
2333                          * and REGS states. The _EN flags must be disabled though.
2334                          */
2335                         rec->flags &= ~(FTRACE_FL_ENABLED | FTRACE_FL_TRAMP_EN |
2336                                         FTRACE_FL_REGS_EN | FTRACE_FL_DIRECT_EN |
2337                                         FTRACE_FL_CALL_OPS_EN);
2338         }
2339
2340         ftrace_bug_type = FTRACE_BUG_NOP;
2341         return FTRACE_UPDATE_MAKE_NOP;
2342 }
2343
2344 /**
2345  * ftrace_update_record - set a record that now is tracing or not
2346  * @rec: the record to update
2347  * @enable: set to true if the record is tracing, false to force disable
2348  *
2349  * The records that represent all functions that can be traced need
2350  * to be updated when tracing has been enabled.
2351  */
2352 int ftrace_update_record(struct dyn_ftrace *rec, bool enable)
2353 {
2354         return ftrace_check_record(rec, enable, true);
2355 }
2356
2357 /**
2358  * ftrace_test_record - check if the record has been enabled or not
2359  * @rec: the record to test
2360  * @enable: set to true to check if enabled, false if it is disabled
2361  *
2362  * The arch code may need to test if a record is already set to
2363  * tracing to determine how to modify the function code that it
2364  * represents.
2365  */
2366 int ftrace_test_record(struct dyn_ftrace *rec, bool enable)
2367 {
2368         return ftrace_check_record(rec, enable, false);
2369 }
2370
2371 static struct ftrace_ops *
2372 ftrace_find_tramp_ops_any(struct dyn_ftrace *rec)
2373 {
2374         struct ftrace_ops *op;
2375         unsigned long ip = rec->ip;
2376
2377         do_for_each_ftrace_op(op, ftrace_ops_list) {
2378
2379                 if (!op->trampoline)
2380                         continue;
2381
2382                 if (hash_contains_ip(ip, op->func_hash))
2383                         return op;
2384         } while_for_each_ftrace_op(op);
2385
2386         return NULL;
2387 }
2388
2389 static struct ftrace_ops *
2390 ftrace_find_tramp_ops_any_other(struct dyn_ftrace *rec, struct ftrace_ops *op_exclude)
2391 {
2392         struct ftrace_ops *op;
2393         unsigned long ip = rec->ip;
2394
2395         do_for_each_ftrace_op(op, ftrace_ops_list) {
2396
2397                 if (op == op_exclude || !op->trampoline)
2398                         continue;
2399
2400                 if (hash_contains_ip(ip, op->func_hash))
2401                         return op;
2402         } while_for_each_ftrace_op(op);
2403
2404         return NULL;
2405 }
2406
2407 static struct ftrace_ops *
2408 ftrace_find_tramp_ops_next(struct dyn_ftrace *rec,
2409                            struct ftrace_ops *op)
2410 {
2411         unsigned long ip = rec->ip;
2412
2413         while_for_each_ftrace_op(op) {
2414
2415                 if (!op->trampoline)
2416                         continue;
2417
2418                 if (hash_contains_ip(ip, op->func_hash))
2419                         return op;
2420         }
2421
2422         return NULL;
2423 }
2424
2425 static struct ftrace_ops *
2426 ftrace_find_tramp_ops_curr(struct dyn_ftrace *rec)
2427 {
2428         struct ftrace_ops *op;
2429         unsigned long ip = rec->ip;
2430
2431         /*
2432          * Need to check removed ops first.
2433          * If they are being removed, and this rec has a tramp,
2434          * and this rec is in the ops list, then it would be the
2435          * one with the tramp.
2436          */
2437         if (removed_ops) {
2438                 if (hash_contains_ip(ip, &removed_ops->old_hash))
2439                         return removed_ops;
2440         }
2441
2442         /*
2443          * Need to find the current trampoline for a rec.
2444          * Now, a trampoline is only attached to a rec if there
2445          * was a single 'ops' attached to it. But this can be called
2446          * when we are adding another op to the rec or removing the
2447          * current one. Thus, if the op is being added, we can
2448          * ignore it because it hasn't attached itself to the rec
2449          * yet.
2450          *
2451          * If an ops is being modified (hooking to different functions)
2452          * then we don't care about the new functions that are being
2453          * added, just the old ones (that are probably being removed).
2454          *
2455          * If we are adding an ops to a function that already is using
2456          * a trampoline, it needs to be removed (trampolines are only
2457          * for single ops connected), then an ops that is not being
2458          * modified also needs to be checked.
2459          */
2460         do_for_each_ftrace_op(op, ftrace_ops_list) {
2461
2462                 if (!op->trampoline)
2463                         continue;
2464
2465                 /*
2466                  * If the ops is being added, it hasn't gotten to
2467                  * the point to be removed from this tree yet.
2468                  */
2469                 if (op->flags & FTRACE_OPS_FL_ADDING)
2470                         continue;
2471
2472
2473                 /*
2474                  * If the ops is being modified and is in the old
2475                  * hash, then it is probably being removed from this
2476                  * function.
2477                  */
2478                 if ((op->flags & FTRACE_OPS_FL_MODIFYING) &&
2479                     hash_contains_ip(ip, &op->old_hash))
2480                         return op;
2481                 /*
2482                  * If the ops is not being added or modified, and it's
2483                  * in its normal filter hash, then this must be the one
2484                  * we want!
2485                  */
2486                 if (!(op->flags & FTRACE_OPS_FL_MODIFYING) &&
2487                     hash_contains_ip(ip, op->func_hash))
2488                         return op;
2489
2490         } while_for_each_ftrace_op(op);
2491
2492         return NULL;
2493 }
2494
2495 static struct ftrace_ops *
2496 ftrace_find_tramp_ops_new(struct dyn_ftrace *rec)
2497 {
2498         struct ftrace_ops *op;
2499         unsigned long ip = rec->ip;
2500
2501         do_for_each_ftrace_op(op, ftrace_ops_list) {
2502                 /* pass rec in as regs to have non-NULL val */
2503                 if (hash_contains_ip(ip, op->func_hash))
2504                         return op;
2505         } while_for_each_ftrace_op(op);
2506
2507         return NULL;
2508 }
2509
2510 struct ftrace_ops *
2511 ftrace_find_unique_ops(struct dyn_ftrace *rec)
2512 {
2513         struct ftrace_ops *op, *found = NULL;
2514         unsigned long ip = rec->ip;
2515
2516         do_for_each_ftrace_op(op, ftrace_ops_list) {
2517
2518                 if (hash_contains_ip(ip, op->func_hash)) {
2519                         if (found)
2520                                 return NULL;
2521                         found = op;
2522                 }
2523
2524         } while_for_each_ftrace_op(op);
2525
2526         return found;
2527 }
2528
2529 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
2530 /* Protected by rcu_tasks for reading, and direct_mutex for writing */
2531 static struct ftrace_hash *direct_functions = EMPTY_HASH;
2532 static DEFINE_MUTEX(direct_mutex);
2533 int ftrace_direct_func_count;
2534
2535 /*
2536  * Search the direct_functions hash to see if the given instruction pointer
2537  * has a direct caller attached to it.
2538  */
2539 unsigned long ftrace_find_rec_direct(unsigned long ip)
2540 {
2541         struct ftrace_func_entry *entry;
2542
2543         entry = __ftrace_lookup_ip(direct_functions, ip);
2544         if (!entry)
2545                 return 0;
2546
2547         return entry->direct;
2548 }
2549
2550 static struct ftrace_func_entry*
2551 ftrace_add_rec_direct(unsigned long ip, unsigned long addr,
2552                       struct ftrace_hash **free_hash)
2553 {
2554         struct ftrace_func_entry *entry;
2555
2556         if (ftrace_hash_empty(direct_functions) ||
2557             direct_functions->count > 2 * (1 << direct_functions->size_bits)) {
2558                 struct ftrace_hash *new_hash;
2559                 int size = ftrace_hash_empty(direct_functions) ? 0 :
2560                         direct_functions->count + 1;
2561
2562                 if (size < 32)
2563                         size = 32;
2564
2565                 new_hash = dup_hash(direct_functions, size);
2566                 if (!new_hash)
2567                         return NULL;
2568
2569                 *free_hash = direct_functions;
2570                 direct_functions = new_hash;
2571         }
2572
2573         entry = kmalloc(sizeof(*entry), GFP_KERNEL);
2574         if (!entry)
2575                 return NULL;
2576
2577         entry->ip = ip;
2578         entry->direct = addr;
2579         __add_hash_entry(direct_functions, entry);
2580         return entry;
2581 }
2582
2583 static void call_direct_funcs(unsigned long ip, unsigned long pip,
2584                               struct ftrace_ops *ops, struct ftrace_regs *fregs)
2585 {
2586         unsigned long addr = READ_ONCE(ops->direct_call);
2587
2588         if (!addr)
2589                 return;
2590
2591         arch_ftrace_set_direct_caller(fregs, addr);
2592 }
2593 #endif /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS */
2594
2595 /**
2596  * ftrace_get_addr_new - Get the call address to set to
2597  * @rec:  The ftrace record descriptor
2598  *
2599  * If the record has the FTRACE_FL_REGS set, that means that it
2600  * wants to convert to a callback that saves all regs. If FTRACE_FL_REGS
2601  * is not set, then it wants to convert to the normal callback.
2602  *
2603  * Returns the address of the trampoline to set to
2604  */
2605 unsigned long ftrace_get_addr_new(struct dyn_ftrace *rec)
2606 {
2607         struct ftrace_ops *ops;
2608         unsigned long addr;
2609
2610         if ((rec->flags & FTRACE_FL_DIRECT) &&
2611             (ftrace_rec_count(rec) == 1)) {
2612                 addr = ftrace_find_rec_direct(rec->ip);
2613                 if (addr)
2614                         return addr;
2615                 WARN_ON_ONCE(1);
2616         }
2617
2618         /* Trampolines take precedence over regs */
2619         if (rec->flags & FTRACE_FL_TRAMP) {
2620                 ops = ftrace_find_tramp_ops_new(rec);
2621                 if (FTRACE_WARN_ON(!ops || !ops->trampoline)) {
2622                         pr_warn("Bad trampoline accounting at: %p (%pS) (%lx)\n",
2623                                 (void *)rec->ip, (void *)rec->ip, rec->flags);
2624                         /* Ftrace is shutting down, return anything */
2625                         return (unsigned long)FTRACE_ADDR;
2626                 }
2627                 return ops->trampoline;
2628         }
2629
2630         if (rec->flags & FTRACE_FL_REGS)
2631                 return (unsigned long)FTRACE_REGS_ADDR;
2632         else
2633                 return (unsigned long)FTRACE_ADDR;
2634 }
2635
2636 /**
2637  * ftrace_get_addr_curr - Get the call address that is already there
2638  * @rec:  The ftrace record descriptor
2639  *
2640  * The FTRACE_FL_REGS_EN is set when the record already points to
2641  * a function that saves all the regs. Basically the '_EN' version
2642  * represents the current state of the function.
2643  *
2644  * Returns the address of the trampoline that is currently being called
2645  */
2646 unsigned long ftrace_get_addr_curr(struct dyn_ftrace *rec)
2647 {
2648         struct ftrace_ops *ops;
2649         unsigned long addr;
2650
2651         /* Direct calls take precedence over trampolines */
2652         if (rec->flags & FTRACE_FL_DIRECT_EN) {
2653                 addr = ftrace_find_rec_direct(rec->ip);
2654                 if (addr)
2655                         return addr;
2656                 WARN_ON_ONCE(1);
2657         }
2658
2659         /* Trampolines take precedence over regs */
2660         if (rec->flags & FTRACE_FL_TRAMP_EN) {
2661                 ops = ftrace_find_tramp_ops_curr(rec);
2662                 if (FTRACE_WARN_ON(!ops)) {
2663                         pr_warn("Bad trampoline accounting at: %p (%pS)\n",
2664                                 (void *)rec->ip, (void *)rec->ip);
2665                         /* Ftrace is shutting down, return anything */
2666                         return (unsigned long)FTRACE_ADDR;
2667                 }
2668                 return ops->trampoline;
2669         }
2670
2671         if (rec->flags & FTRACE_FL_REGS_EN)
2672                 return (unsigned long)FTRACE_REGS_ADDR;
2673         else
2674                 return (unsigned long)FTRACE_ADDR;
2675 }
2676
2677 static int
2678 __ftrace_replace_code(struct dyn_ftrace *rec, bool enable)
2679 {
2680         unsigned long ftrace_old_addr;
2681         unsigned long ftrace_addr;
2682         int ret;
2683
2684         ftrace_addr = ftrace_get_addr_new(rec);
2685
2686         /* This needs to be done before we call ftrace_update_record */
2687         ftrace_old_addr = ftrace_get_addr_curr(rec);
2688
2689         ret = ftrace_update_record(rec, enable);
2690
2691         ftrace_bug_type = FTRACE_BUG_UNKNOWN;
2692
2693         switch (ret) {
2694         case FTRACE_UPDATE_IGNORE:
2695                 return 0;
2696
2697         case FTRACE_UPDATE_MAKE_CALL:
2698                 ftrace_bug_type = FTRACE_BUG_CALL;
2699                 return ftrace_make_call(rec, ftrace_addr);
2700
2701         case FTRACE_UPDATE_MAKE_NOP:
2702                 ftrace_bug_type = FTRACE_BUG_NOP;
2703                 return ftrace_make_nop(NULL, rec, ftrace_old_addr);
2704
2705         case FTRACE_UPDATE_MODIFY_CALL:
2706                 ftrace_bug_type = FTRACE_BUG_UPDATE;
2707                 return ftrace_modify_call(rec, ftrace_old_addr, ftrace_addr);
2708         }
2709
2710         return -1; /* unknown ftrace bug */
2711 }
2712
2713 void __weak ftrace_replace_code(int mod_flags)
2714 {
2715         struct dyn_ftrace *rec;
2716         struct ftrace_page *pg;
2717         bool enable = mod_flags & FTRACE_MODIFY_ENABLE_FL;
2718         int schedulable = mod_flags & FTRACE_MODIFY_MAY_SLEEP_FL;
2719         int failed;
2720
2721         if (unlikely(ftrace_disabled))
2722                 return;
2723
2724         do_for_each_ftrace_rec(pg, rec) {
2725
2726                 if (skip_record(rec))
2727                         continue;
2728
2729                 failed = __ftrace_replace_code(rec, enable);
2730                 if (failed) {
2731                         ftrace_bug(failed, rec);
2732                         /* Stop processing */
2733                         return;
2734                 }
2735                 if (schedulable)
2736                         cond_resched();
2737         } while_for_each_ftrace_rec();
2738 }
2739
2740 struct ftrace_rec_iter {
2741         struct ftrace_page      *pg;
2742         int                     index;
2743 };
2744
2745 /**
2746  * ftrace_rec_iter_start - start up iterating over traced functions
2747  *
2748  * Returns an iterator handle that is used to iterate over all
2749  * the records that represent address locations where functions
2750  * are traced.
2751  *
2752  * May return NULL if no records are available.
2753  */
2754 struct ftrace_rec_iter *ftrace_rec_iter_start(void)
2755 {
2756         /*
2757          * We only use a single iterator.
2758          * Protected by the ftrace_lock mutex.
2759          */
2760         static struct ftrace_rec_iter ftrace_rec_iter;
2761         struct ftrace_rec_iter *iter = &ftrace_rec_iter;
2762
2763         iter->pg = ftrace_pages_start;
2764         iter->index = 0;
2765
2766         /* Could have empty pages */
2767         while (iter->pg && !iter->pg->index)
2768                 iter->pg = iter->pg->next;
2769
2770         if (!iter->pg)
2771                 return NULL;
2772
2773         return iter;
2774 }
2775
2776 /**
2777  * ftrace_rec_iter_next - get the next record to process.
2778  * @iter: The handle to the iterator.
2779  *
2780  * Returns the next iterator after the given iterator @iter.
2781  */
2782 struct ftrace_rec_iter *ftrace_rec_iter_next(struct ftrace_rec_iter *iter)
2783 {
2784         iter->index++;
2785
2786         if (iter->index >= iter->pg->index) {
2787                 iter->pg = iter->pg->next;
2788                 iter->index = 0;
2789
2790                 /* Could have empty pages */
2791                 while (iter->pg && !iter->pg->index)
2792                         iter->pg = iter->pg->next;
2793         }
2794
2795         if (!iter->pg)
2796                 return NULL;
2797
2798         return iter;
2799 }
2800
2801 /**
2802  * ftrace_rec_iter_record - get the record at the iterator location
2803  * @iter: The current iterator location
2804  *
2805  * Returns the record that the current @iter is at.
2806  */
2807 struct dyn_ftrace *ftrace_rec_iter_record(struct ftrace_rec_iter *iter)
2808 {
2809         return &iter->pg->records[iter->index];
2810 }
2811
2812 static int
2813 ftrace_nop_initialize(struct module *mod, struct dyn_ftrace *rec)
2814 {
2815         int ret;
2816
2817         if (unlikely(ftrace_disabled))
2818                 return 0;
2819
2820         ret = ftrace_init_nop(mod, rec);
2821         if (ret) {
2822                 ftrace_bug_type = FTRACE_BUG_INIT;
2823                 ftrace_bug(ret, rec);
2824                 return 0;
2825         }
2826         return 1;
2827 }
2828
2829 /*
2830  * archs can override this function if they must do something
2831  * before the modifying code is performed.
2832  */
2833 void __weak ftrace_arch_code_modify_prepare(void)
2834 {
2835 }
2836
2837 /*
2838  * archs can override this function if they must do something
2839  * after the modifying code is performed.
2840  */
2841 void __weak ftrace_arch_code_modify_post_process(void)
2842 {
2843 }
2844
2845 static int update_ftrace_func(ftrace_func_t func)
2846 {
2847         static ftrace_func_t save_func;
2848
2849         /* Avoid updating if it hasn't changed */
2850         if (func == save_func)
2851                 return 0;
2852
2853         save_func = func;
2854
2855         return ftrace_update_ftrace_func(func);
2856 }
2857
2858 void ftrace_modify_all_code(int command)
2859 {
2860         int update = command & FTRACE_UPDATE_TRACE_FUNC;
2861         int mod_flags = 0;
2862         int err = 0;
2863
2864         if (command & FTRACE_MAY_SLEEP)
2865                 mod_flags = FTRACE_MODIFY_MAY_SLEEP_FL;
2866
2867         /*
2868          * If the ftrace_caller calls a ftrace_ops func directly,
2869          * we need to make sure that it only traces functions it
2870          * expects to trace. When doing the switch of functions,
2871          * we need to update to the ftrace_ops_list_func first
2872          * before the transition between old and new calls are set,
2873          * as the ftrace_ops_list_func will check the ops hashes
2874          * to make sure the ops are having the right functions
2875          * traced.
2876          */
2877         if (update) {
2878                 err = update_ftrace_func(ftrace_ops_list_func);
2879                 if (FTRACE_WARN_ON(err))
2880                         return;
2881         }
2882
2883         if (command & FTRACE_UPDATE_CALLS)
2884                 ftrace_replace_code(mod_flags | FTRACE_MODIFY_ENABLE_FL);
2885         else if (command & FTRACE_DISABLE_CALLS)
2886                 ftrace_replace_code(mod_flags);
2887
2888         if (update && ftrace_trace_function != ftrace_ops_list_func) {
2889                 function_trace_op = set_function_trace_op;
2890                 smp_wmb();
2891                 /* If irqs are disabled, we are in stop machine */
2892                 if (!irqs_disabled())
2893                         smp_call_function(ftrace_sync_ipi, NULL, 1);
2894                 err = update_ftrace_func(ftrace_trace_function);
2895                 if (FTRACE_WARN_ON(err))
2896                         return;
2897         }
2898
2899         if (command & FTRACE_START_FUNC_RET)
2900                 err = ftrace_enable_ftrace_graph_caller();
2901         else if (command & FTRACE_STOP_FUNC_RET)
2902                 err = ftrace_disable_ftrace_graph_caller();
2903         FTRACE_WARN_ON(err);
2904 }
2905
2906 static int __ftrace_modify_code(void *data)
2907 {
2908         int *command = data;
2909
2910         ftrace_modify_all_code(*command);
2911
2912         return 0;
2913 }
2914
2915 /**
2916  * ftrace_run_stop_machine - go back to the stop machine method
2917  * @command: The command to tell ftrace what to do
2918  *
2919  * If an arch needs to fall back to the stop machine method, the
2920  * it can call this function.
2921  */
2922 void ftrace_run_stop_machine(int command)
2923 {
2924         stop_machine(__ftrace_modify_code, &command, NULL);
2925 }
2926
2927 /**
2928  * arch_ftrace_update_code - modify the code to trace or not trace
2929  * @command: The command that needs to be done
2930  *
2931  * Archs can override this function if it does not need to
2932  * run stop_machine() to modify code.
2933  */
2934 void __weak arch_ftrace_update_code(int command)
2935 {
2936         ftrace_run_stop_machine(command);
2937 }
2938
2939 static void ftrace_run_update_code(int command)
2940 {
2941         ftrace_arch_code_modify_prepare();
2942
2943         /*
2944          * By default we use stop_machine() to modify the code.
2945          * But archs can do what ever they want as long as it
2946          * is safe. The stop_machine() is the safest, but also
2947          * produces the most overhead.
2948          */
2949         arch_ftrace_update_code(command);
2950
2951         ftrace_arch_code_modify_post_process();
2952 }
2953
2954 static void ftrace_run_modify_code(struct ftrace_ops *ops, int command,
2955                                    struct ftrace_ops_hash *old_hash)
2956 {
2957         ops->flags |= FTRACE_OPS_FL_MODIFYING;
2958         ops->old_hash.filter_hash = old_hash->filter_hash;
2959         ops->old_hash.notrace_hash = old_hash->notrace_hash;
2960         ftrace_run_update_code(command);
2961         ops->old_hash.filter_hash = NULL;
2962         ops->old_hash.notrace_hash = NULL;
2963         ops->flags &= ~FTRACE_OPS_FL_MODIFYING;
2964 }
2965
2966 static ftrace_func_t saved_ftrace_func;
2967 static int ftrace_start_up;
2968
2969 void __weak arch_ftrace_trampoline_free(struct ftrace_ops *ops)
2970 {
2971 }
2972
2973 /* List of trace_ops that have allocated trampolines */
2974 static LIST_HEAD(ftrace_ops_trampoline_list);
2975
2976 static void ftrace_add_trampoline_to_kallsyms(struct ftrace_ops *ops)
2977 {
2978         lockdep_assert_held(&ftrace_lock);
2979         list_add_rcu(&ops->list, &ftrace_ops_trampoline_list);
2980 }
2981
2982 static void ftrace_remove_trampoline_from_kallsyms(struct ftrace_ops *ops)
2983 {
2984         lockdep_assert_held(&ftrace_lock);
2985         list_del_rcu(&ops->list);
2986         synchronize_rcu();
2987 }
2988
2989 /*
2990  * "__builtin__ftrace" is used as a module name in /proc/kallsyms for symbols
2991  * for pages allocated for ftrace purposes, even though "__builtin__ftrace" is
2992  * not a module.
2993  */
2994 #define FTRACE_TRAMPOLINE_MOD "__builtin__ftrace"
2995 #define FTRACE_TRAMPOLINE_SYM "ftrace_trampoline"
2996
2997 static void ftrace_trampoline_free(struct ftrace_ops *ops)
2998 {
2999         if (ops && (ops->flags & FTRACE_OPS_FL_ALLOC_TRAMP) &&
3000             ops->trampoline) {
3001                 /*
3002                  * Record the text poke event before the ksymbol unregister
3003                  * event.
3004                  */
3005                 perf_event_text_poke((void *)ops->trampoline,
3006                                      (void *)ops->trampoline,
3007                                      ops->trampoline_size, NULL, 0);
3008                 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_OOL,
3009                                    ops->trampoline, ops->trampoline_size,
3010                                    true, FTRACE_TRAMPOLINE_SYM);
3011                 /* Remove from kallsyms after the perf events */
3012                 ftrace_remove_trampoline_from_kallsyms(ops);
3013         }
3014
3015         arch_ftrace_trampoline_free(ops);
3016 }
3017
3018 static void ftrace_startup_enable(int command)
3019 {
3020         if (saved_ftrace_func != ftrace_trace_function) {
3021                 saved_ftrace_func = ftrace_trace_function;
3022                 command |= FTRACE_UPDATE_TRACE_FUNC;
3023         }
3024
3025         if (!command || !ftrace_enabled)
3026                 return;
3027
3028         ftrace_run_update_code(command);
3029 }
3030
3031 static void ftrace_startup_all(int command)
3032 {
3033         update_all_ops = true;
3034         ftrace_startup_enable(command);
3035         update_all_ops = false;
3036 }
3037
3038 int ftrace_startup(struct ftrace_ops *ops, int command)
3039 {
3040         int ret;
3041
3042         if (unlikely(ftrace_disabled))
3043                 return -ENODEV;
3044
3045         ret = __register_ftrace_function(ops);
3046         if (ret)
3047                 return ret;
3048
3049         ftrace_start_up++;
3050
3051         /*
3052          * Note that ftrace probes uses this to start up
3053          * and modify functions it will probe. But we still
3054          * set the ADDING flag for modification, as probes
3055          * do not have trampolines. If they add them in the
3056          * future, then the probes will need to distinguish
3057          * between adding and updating probes.
3058          */
3059         ops->flags |= FTRACE_OPS_FL_ENABLED | FTRACE_OPS_FL_ADDING;
3060
3061         ret = ftrace_hash_ipmodify_enable(ops);
3062         if (ret < 0) {
3063                 /* Rollback registration process */
3064                 __unregister_ftrace_function(ops);
3065                 ftrace_start_up--;
3066                 ops->flags &= ~FTRACE_OPS_FL_ENABLED;
3067                 if (ops->flags & FTRACE_OPS_FL_DYNAMIC)
3068                         ftrace_trampoline_free(ops);
3069                 return ret;
3070         }
3071
3072         if (ftrace_hash_rec_enable(ops, 1))
3073                 command |= FTRACE_UPDATE_CALLS;
3074
3075         ftrace_startup_enable(command);
3076
3077         /*
3078          * If ftrace is in an undefined state, we just remove ops from list
3079          * to prevent the NULL pointer, instead of totally rolling it back and
3080          * free trampoline, because those actions could cause further damage.
3081          */
3082         if (unlikely(ftrace_disabled)) {
3083                 __unregister_ftrace_function(ops);
3084                 return -ENODEV;
3085         }
3086
3087         ops->flags &= ~FTRACE_OPS_FL_ADDING;
3088
3089         return 0;
3090 }
3091
3092 int ftrace_shutdown(struct ftrace_ops *ops, int command)
3093 {
3094         int ret;
3095
3096         if (unlikely(ftrace_disabled))
3097                 return -ENODEV;
3098
3099         ret = __unregister_ftrace_function(ops);
3100         if (ret)
3101                 return ret;
3102
3103         ftrace_start_up--;
3104         /*
3105          * Just warn in case of unbalance, no need to kill ftrace, it's not
3106          * critical but the ftrace_call callers may be never nopped again after
3107          * further ftrace uses.
3108          */
3109         WARN_ON_ONCE(ftrace_start_up < 0);
3110
3111         /* Disabling ipmodify never fails */
3112         ftrace_hash_ipmodify_disable(ops);
3113
3114         if (ftrace_hash_rec_disable(ops, 1))
3115                 command |= FTRACE_UPDATE_CALLS;
3116
3117         ops->flags &= ~FTRACE_OPS_FL_ENABLED;
3118
3119         if (saved_ftrace_func != ftrace_trace_function) {
3120                 saved_ftrace_func = ftrace_trace_function;
3121                 command |= FTRACE_UPDATE_TRACE_FUNC;
3122         }
3123
3124         if (!command || !ftrace_enabled)
3125                 goto out;
3126
3127         /*
3128          * If the ops uses a trampoline, then it needs to be
3129          * tested first on update.
3130          */
3131         ops->flags |= FTRACE_OPS_FL_REMOVING;
3132         removed_ops = ops;
3133
3134         /* The trampoline logic checks the old hashes */
3135         ops->old_hash.filter_hash = ops->func_hash->filter_hash;
3136         ops->old_hash.notrace_hash = ops->func_hash->notrace_hash;
3137
3138         ftrace_run_update_code(command);
3139
3140         /*
3141          * If there's no more ops registered with ftrace, run a
3142          * sanity check to make sure all rec flags are cleared.
3143          */
3144         if (rcu_dereference_protected(ftrace_ops_list,
3145                         lockdep_is_held(&ftrace_lock)) == &ftrace_list_end) {
3146                 struct ftrace_page *pg;
3147                 struct dyn_ftrace *rec;
3148
3149                 do_for_each_ftrace_rec(pg, rec) {
3150                         if (FTRACE_WARN_ON_ONCE(rec->flags & ~FTRACE_FL_DISABLED))
3151                                 pr_warn("  %pS flags:%lx\n",
3152                                         (void *)rec->ip, rec->flags);
3153                 } while_for_each_ftrace_rec();
3154         }
3155
3156         ops->old_hash.filter_hash = NULL;
3157         ops->old_hash.notrace_hash = NULL;
3158
3159         removed_ops = NULL;
3160         ops->flags &= ~FTRACE_OPS_FL_REMOVING;
3161
3162 out:
3163         /*
3164          * Dynamic ops may be freed, we must make sure that all
3165          * callers are done before leaving this function.
3166          */
3167         if (ops->flags & FTRACE_OPS_FL_DYNAMIC) {
3168                 /*
3169                  * We need to do a hard force of sched synchronization.
3170                  * This is because we use preempt_disable() to do RCU, but
3171                  * the function tracers can be called where RCU is not watching
3172                  * (like before user_exit()). We can not rely on the RCU
3173                  * infrastructure to do the synchronization, thus we must do it
3174                  * ourselves.
3175                  */
3176                 synchronize_rcu_tasks_rude();
3177
3178                 /*
3179                  * When the kernel is preemptive, tasks can be preempted
3180                  * while on a ftrace trampoline. Just scheduling a task on
3181                  * a CPU is not good enough to flush them. Calling
3182                  * synchronize_rcu_tasks() will wait for those tasks to
3183                  * execute and either schedule voluntarily or enter user space.
3184                  */
3185                 if (IS_ENABLED(CONFIG_PREEMPTION))
3186                         synchronize_rcu_tasks();
3187
3188                 ftrace_trampoline_free(ops);
3189         }
3190
3191         return 0;
3192 }
3193
3194 static u64              ftrace_update_time;
3195 unsigned long           ftrace_update_tot_cnt;
3196 unsigned long           ftrace_number_of_pages;
3197 unsigned long           ftrace_number_of_groups;
3198
3199 static inline int ops_traces_mod(struct ftrace_ops *ops)
3200 {
3201         /*
3202          * Filter_hash being empty will default to trace module.
3203          * But notrace hash requires a test of individual module functions.
3204          */
3205         return ftrace_hash_empty(ops->func_hash->filter_hash) &&
3206                 ftrace_hash_empty(ops->func_hash->notrace_hash);
3207 }
3208
3209 static int ftrace_update_code(struct module *mod, struct ftrace_page *new_pgs)
3210 {
3211         bool init_nop = ftrace_need_init_nop();
3212         struct ftrace_page *pg;
3213         struct dyn_ftrace *p;
3214         u64 start, stop;
3215         unsigned long update_cnt = 0;
3216         unsigned long rec_flags = 0;
3217         int i;
3218
3219         start = ftrace_now(raw_smp_processor_id());
3220
3221         /*
3222          * When a module is loaded, this function is called to convert
3223          * the calls to mcount in its text to nops, and also to create
3224          * an entry in the ftrace data. Now, if ftrace is activated
3225          * after this call, but before the module sets its text to
3226          * read-only, the modification of enabling ftrace can fail if
3227          * the read-only is done while ftrace is converting the calls.
3228          * To prevent this, the module's records are set as disabled
3229          * and will be enabled after the call to set the module's text
3230          * to read-only.
3231          */
3232         if (mod)
3233                 rec_flags |= FTRACE_FL_DISABLED;
3234
3235         for (pg = new_pgs; pg; pg = pg->next) {
3236
3237                 for (i = 0; i < pg->index; i++) {
3238
3239                         /* If something went wrong, bail without enabling anything */
3240                         if (unlikely(ftrace_disabled))
3241                                 return -1;
3242
3243                         p = &pg->records[i];
3244                         p->flags = rec_flags;
3245
3246                         /*
3247                          * Do the initial record conversion from mcount jump
3248                          * to the NOP instructions.
3249                          */
3250                         if (init_nop && !ftrace_nop_initialize(mod, p))
3251                                 break;
3252
3253                         update_cnt++;
3254                 }
3255         }
3256
3257         stop = ftrace_now(raw_smp_processor_id());
3258         ftrace_update_time = stop - start;
3259         ftrace_update_tot_cnt += update_cnt;
3260
3261         return 0;
3262 }
3263
3264 static int ftrace_allocate_records(struct ftrace_page *pg, int count)
3265 {
3266         int order;
3267         int pages;
3268         int cnt;
3269
3270         if (WARN_ON(!count))
3271                 return -EINVAL;
3272
3273         /* We want to fill as much as possible, with no empty pages */
3274         pages = DIV_ROUND_UP(count, ENTRIES_PER_PAGE);
3275         order = fls(pages) - 1;
3276
3277  again:
3278         pg->records = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO, order);
3279
3280         if (!pg->records) {
3281                 /* if we can't allocate this size, try something smaller */
3282                 if (!order)
3283                         return -ENOMEM;
3284                 order--;
3285                 goto again;
3286         }
3287
3288         ftrace_number_of_pages += 1 << order;
3289         ftrace_number_of_groups++;
3290
3291         cnt = (PAGE_SIZE << order) / ENTRY_SIZE;
3292         pg->order = order;
3293
3294         if (cnt > count)
3295                 cnt = count;
3296
3297         return cnt;
3298 }
3299
3300 static struct ftrace_page *
3301 ftrace_allocate_pages(unsigned long num_to_init)
3302 {
3303         struct ftrace_page *start_pg;
3304         struct ftrace_page *pg;
3305         int cnt;
3306
3307         if (!num_to_init)
3308                 return NULL;
3309
3310         start_pg = pg = kzalloc(sizeof(*pg), GFP_KERNEL);
3311         if (!pg)
3312                 return NULL;
3313
3314         /*
3315          * Try to allocate as much as possible in one continues
3316          * location that fills in all of the space. We want to
3317          * waste as little space as possible.
3318          */
3319         for (;;) {
3320                 cnt = ftrace_allocate_records(pg, num_to_init);
3321                 if (cnt < 0)
3322                         goto free_pages;
3323
3324                 num_to_init -= cnt;
3325                 if (!num_to_init)
3326                         break;
3327
3328                 pg->next = kzalloc(sizeof(*pg), GFP_KERNEL);
3329                 if (!pg->next)
3330                         goto free_pages;
3331
3332                 pg = pg->next;
3333         }
3334
3335         return start_pg;
3336
3337  free_pages:
3338         pg = start_pg;
3339         while (pg) {
3340                 if (pg->records) {
3341                         free_pages((unsigned long)pg->records, pg->order);
3342                         ftrace_number_of_pages -= 1 << pg->order;
3343                 }
3344                 start_pg = pg->next;
3345                 kfree(pg);
3346                 pg = start_pg;
3347                 ftrace_number_of_groups--;
3348         }
3349         pr_info("ftrace: FAILED to allocate memory for functions\n");
3350         return NULL;
3351 }
3352
3353 #define FTRACE_BUFF_MAX (KSYM_SYMBOL_LEN+4) /* room for wildcards */
3354
3355 struct ftrace_iterator {
3356         loff_t                          pos;
3357         loff_t                          func_pos;
3358         loff_t                          mod_pos;
3359         struct ftrace_page              *pg;
3360         struct dyn_ftrace               *func;
3361         struct ftrace_func_probe        *probe;
3362         struct ftrace_func_entry        *probe_entry;
3363         struct trace_parser             parser;
3364         struct ftrace_hash              *hash;
3365         struct ftrace_ops               *ops;
3366         struct trace_array              *tr;
3367         struct list_head                *mod_list;
3368         int                             pidx;
3369         int                             idx;
3370         unsigned                        flags;
3371 };
3372
3373 static void *
3374 t_probe_next(struct seq_file *m, loff_t *pos)
3375 {
3376         struct ftrace_iterator *iter = m->private;
3377         struct trace_array *tr = iter->ops->private;
3378         struct list_head *func_probes;
3379         struct ftrace_hash *hash;
3380         struct list_head *next;
3381         struct hlist_node *hnd = NULL;
3382         struct hlist_head *hhd;
3383         int size;
3384
3385         (*pos)++;
3386         iter->pos = *pos;
3387
3388         if (!tr)
3389                 return NULL;
3390
3391         func_probes = &tr->func_probes;
3392         if (list_empty(func_probes))
3393                 return NULL;
3394
3395         if (!iter->probe) {
3396                 next = func_probes->next;
3397                 iter->probe = list_entry(next, struct ftrace_func_probe, list);
3398         }
3399
3400         if (iter->probe_entry)
3401                 hnd = &iter->probe_entry->hlist;
3402
3403         hash = iter->probe->ops.func_hash->filter_hash;
3404
3405         /*
3406          * A probe being registered may temporarily have an empty hash
3407          * and it's at the end of the func_probes list.
3408          */
3409         if (!hash || hash == EMPTY_HASH)
3410                 return NULL;
3411
3412         size = 1 << hash->size_bits;
3413
3414  retry:
3415         if (iter->pidx >= size) {
3416                 if (iter->probe->list.next == func_probes)
3417                         return NULL;
3418                 next = iter->probe->list.next;
3419                 iter->probe = list_entry(next, struct ftrace_func_probe, list);
3420                 hash = iter->probe->ops.func_hash->filter_hash;
3421                 size = 1 << hash->size_bits;
3422                 iter->pidx = 0;
3423         }
3424
3425         hhd = &hash->buckets[iter->pidx];
3426
3427         if (hlist_empty(hhd)) {
3428                 iter->pidx++;
3429                 hnd = NULL;
3430                 goto retry;
3431         }
3432
3433         if (!hnd)
3434                 hnd = hhd->first;
3435         else {
3436                 hnd = hnd->next;
3437                 if (!hnd) {
3438                         iter->pidx++;
3439                         goto retry;
3440                 }
3441         }
3442
3443         if (WARN_ON_ONCE(!hnd))
3444                 return NULL;
3445
3446         iter->probe_entry = hlist_entry(hnd, struct ftrace_func_entry, hlist);
3447
3448         return iter;
3449 }
3450
3451 static void *t_probe_start(struct seq_file *m, loff_t *pos)
3452 {
3453         struct ftrace_iterator *iter = m->private;
3454         void *p = NULL;
3455         loff_t l;
3456
3457         if (!(iter->flags & FTRACE_ITER_DO_PROBES))
3458                 return NULL;
3459
3460         if (iter->mod_pos > *pos)
3461                 return NULL;
3462
3463         iter->probe = NULL;
3464         iter->probe_entry = NULL;
3465         iter->pidx = 0;
3466         for (l = 0; l <= (*pos - iter->mod_pos); ) {
3467                 p = t_probe_next(m, &l);
3468                 if (!p)
3469                         break;
3470         }
3471         if (!p)
3472                 return NULL;
3473
3474         /* Only set this if we have an item */
3475         iter->flags |= FTRACE_ITER_PROBE;
3476
3477         return iter;
3478 }
3479
3480 static int
3481 t_probe_show(struct seq_file *m, struct ftrace_iterator *iter)
3482 {
3483         struct ftrace_func_entry *probe_entry;
3484         struct ftrace_probe_ops *probe_ops;
3485         struct ftrace_func_probe *probe;
3486
3487         probe = iter->probe;
3488         probe_entry = iter->probe_entry;
3489
3490         if (WARN_ON_ONCE(!probe || !probe_entry))
3491                 return -EIO;
3492
3493         probe_ops = probe->probe_ops;
3494
3495         if (probe_ops->print)
3496                 return probe_ops->print(m, probe_entry->ip, probe_ops, probe->data);
3497
3498         seq_printf(m, "%ps:%ps\n", (void *)probe_entry->ip,
3499                    (void *)probe_ops->func);
3500
3501         return 0;
3502 }
3503
3504 static void *
3505 t_mod_next(struct seq_file *m, loff_t *pos)
3506 {
3507         struct ftrace_iterator *iter = m->private;
3508         struct trace_array *tr = iter->tr;
3509
3510         (*pos)++;
3511         iter->pos = *pos;
3512
3513         iter->mod_list = iter->mod_list->next;
3514
3515         if (iter->mod_list == &tr->mod_trace ||
3516             iter->mod_list == &tr->mod_notrace) {
3517                 iter->flags &= ~FTRACE_ITER_MOD;
3518                 return NULL;
3519         }
3520
3521         iter->mod_pos = *pos;
3522
3523         return iter;
3524 }
3525
3526 static void *t_mod_start(struct seq_file *m, loff_t *pos)
3527 {
3528         struct ftrace_iterator *iter = m->private;
3529         void *p = NULL;
3530         loff_t l;
3531
3532         if (iter->func_pos > *pos)
3533                 return NULL;
3534
3535         iter->mod_pos = iter->func_pos;
3536
3537         /* probes are only available if tr is set */
3538         if (!iter->tr)
3539                 return NULL;
3540
3541         for (l = 0; l <= (*pos - iter->func_pos); ) {
3542                 p = t_mod_next(m, &l);
3543                 if (!p)
3544                         break;
3545         }
3546         if (!p) {
3547                 iter->flags &= ~FTRACE_ITER_MOD;
3548                 return t_probe_start(m, pos);
3549         }
3550
3551         /* Only set this if we have an item */
3552         iter->flags |= FTRACE_ITER_MOD;
3553
3554         return iter;
3555 }
3556
3557 static int
3558 t_mod_show(struct seq_file *m, struct ftrace_iterator *iter)
3559 {
3560         struct ftrace_mod_load *ftrace_mod;
3561         struct trace_array *tr = iter->tr;
3562
3563         if (WARN_ON_ONCE(!iter->mod_list) ||
3564                          iter->mod_list == &tr->mod_trace ||
3565                          iter->mod_list == &tr->mod_notrace)
3566                 return -EIO;
3567
3568         ftrace_mod = list_entry(iter->mod_list, struct ftrace_mod_load, list);
3569
3570         if (ftrace_mod->func)
3571                 seq_printf(m, "%s", ftrace_mod->func);
3572         else
3573                 seq_putc(m, '*');
3574
3575         seq_printf(m, ":mod:%s\n", ftrace_mod->module);
3576
3577         return 0;
3578 }
3579
3580 static void *
3581 t_func_next(struct seq_file *m, loff_t *pos)
3582 {
3583         struct ftrace_iterator *iter = m->private;
3584         struct dyn_ftrace *rec = NULL;
3585
3586         (*pos)++;
3587
3588  retry:
3589         if (iter->idx >= iter->pg->index) {
3590                 if (iter->pg->next) {
3591                         iter->pg = iter->pg->next;
3592                         iter->idx = 0;
3593                         goto retry;
3594                 }
3595         } else {
3596                 rec = &iter->pg->records[iter->idx++];
3597                 if (((iter->flags & (FTRACE_ITER_FILTER | FTRACE_ITER_NOTRACE)) &&
3598                      !ftrace_lookup_ip(iter->hash, rec->ip)) ||
3599
3600                     ((iter->flags & FTRACE_ITER_ENABLED) &&
3601                      !(rec->flags & FTRACE_FL_ENABLED))) {
3602
3603                         rec = NULL;
3604                         goto retry;
3605                 }
3606         }
3607
3608         if (!rec)
3609                 return NULL;
3610
3611         iter->pos = iter->func_pos = *pos;
3612         iter->func = rec;
3613
3614         return iter;
3615 }
3616
3617 static void *
3618 t_next(struct seq_file *m, void *v, loff_t *pos)
3619 {
3620         struct ftrace_iterator *iter = m->private;
3621         loff_t l = *pos; /* t_probe_start() must use original pos */
3622         void *ret;
3623
3624         if (unlikely(ftrace_disabled))
3625                 return NULL;
3626
3627         if (iter->flags & FTRACE_ITER_PROBE)
3628                 return t_probe_next(m, pos);
3629
3630         if (iter->flags & FTRACE_ITER_MOD)
3631                 return t_mod_next(m, pos);
3632
3633         if (iter->flags & FTRACE_ITER_PRINTALL) {
3634                 /* next must increment pos, and t_probe_start does not */
3635                 (*pos)++;
3636                 return t_mod_start(m, &l);
3637         }
3638
3639         ret = t_func_next(m, pos);
3640
3641         if (!ret)
3642                 return t_mod_start(m, &l);
3643
3644         return ret;
3645 }
3646
3647 static void reset_iter_read(struct ftrace_iterator *iter)
3648 {
3649         iter->pos = 0;
3650         iter->func_pos = 0;
3651         iter->flags &= ~(FTRACE_ITER_PRINTALL | FTRACE_ITER_PROBE | FTRACE_ITER_MOD);
3652 }
3653
3654 static void *t_start(struct seq_file *m, loff_t *pos)
3655 {
3656         struct ftrace_iterator *iter = m->private;
3657         void *p = NULL;
3658         loff_t l;
3659
3660         mutex_lock(&ftrace_lock);
3661
3662         if (unlikely(ftrace_disabled))
3663                 return NULL;
3664
3665         /*
3666          * If an lseek was done, then reset and start from beginning.
3667          */
3668         if (*pos < iter->pos)
3669                 reset_iter_read(iter);
3670
3671         /*
3672          * For set_ftrace_filter reading, if we have the filter
3673          * off, we can short cut and just print out that all
3674          * functions are enabled.
3675          */
3676         if ((iter->flags & (FTRACE_ITER_FILTER | FTRACE_ITER_NOTRACE)) &&
3677             ftrace_hash_empty(iter->hash)) {
3678                 iter->func_pos = 1; /* Account for the message */
3679                 if (*pos > 0)
3680                         return t_mod_start(m, pos);
3681                 iter->flags |= FTRACE_ITER_PRINTALL;
3682                 /* reset in case of seek/pread */
3683                 iter->flags &= ~FTRACE_ITER_PROBE;
3684                 return iter;
3685         }
3686
3687         if (iter->flags & FTRACE_ITER_MOD)
3688                 return t_mod_start(m, pos);
3689
3690         /*
3691          * Unfortunately, we need to restart at ftrace_pages_start
3692          * every time we let go of the ftrace_mutex. This is because
3693          * those pointers can change without the lock.
3694          */
3695         iter->pg = ftrace_pages_start;
3696         iter->idx = 0;
3697         for (l = 0; l <= *pos; ) {
3698                 p = t_func_next(m, &l);
3699                 if (!p)
3700                         break;
3701         }
3702
3703         if (!p)
3704                 return t_mod_start(m, pos);
3705
3706         return iter;
3707 }
3708
3709 static void t_stop(struct seq_file *m, void *p)
3710 {
3711         mutex_unlock(&ftrace_lock);
3712 }
3713
3714 void * __weak
3715 arch_ftrace_trampoline_func(struct ftrace_ops *ops, struct dyn_ftrace *rec)
3716 {
3717         return NULL;
3718 }
3719
3720 static void add_trampoline_func(struct seq_file *m, struct ftrace_ops *ops,
3721                                 struct dyn_ftrace *rec)
3722 {
3723         void *ptr;
3724
3725         ptr = arch_ftrace_trampoline_func(ops, rec);
3726         if (ptr)
3727                 seq_printf(m, " ->%pS", ptr);
3728 }
3729
3730 #ifdef FTRACE_MCOUNT_MAX_OFFSET
3731 /*
3732  * Weak functions can still have an mcount/fentry that is saved in
3733  * the __mcount_loc section. These can be detected by having a
3734  * symbol offset of greater than FTRACE_MCOUNT_MAX_OFFSET, as the
3735  * symbol found by kallsyms is not the function that the mcount/fentry
3736  * is part of. The offset is much greater in these cases.
3737  *
3738  * Test the record to make sure that the ip points to a valid kallsyms
3739  * and if not, mark it disabled.
3740  */
3741 static int test_for_valid_rec(struct dyn_ftrace *rec)
3742 {
3743         char str[KSYM_SYMBOL_LEN];
3744         unsigned long offset;
3745         const char *ret;
3746
3747         ret = kallsyms_lookup(rec->ip, NULL, &offset, NULL, str);
3748
3749         /* Weak functions can cause invalid addresses */
3750         if (!ret || offset > FTRACE_MCOUNT_MAX_OFFSET) {
3751                 rec->flags |= FTRACE_FL_DISABLED;
3752                 return 0;
3753         }
3754         return 1;
3755 }
3756
3757 static struct workqueue_struct *ftrace_check_wq __initdata;
3758 static struct work_struct ftrace_check_work __initdata;
3759
3760 /*
3761  * Scan all the mcount/fentry entries to make sure they are valid.
3762  */
3763 static __init void ftrace_check_work_func(struct work_struct *work)
3764 {
3765         struct ftrace_page *pg;
3766         struct dyn_ftrace *rec;
3767
3768         mutex_lock(&ftrace_lock);
3769         do_for_each_ftrace_rec(pg, rec) {
3770                 test_for_valid_rec(rec);
3771         } while_for_each_ftrace_rec();
3772         mutex_unlock(&ftrace_lock);
3773 }
3774
3775 static int __init ftrace_check_for_weak_functions(void)
3776 {
3777         INIT_WORK(&ftrace_check_work, ftrace_check_work_func);
3778
3779         ftrace_check_wq = alloc_workqueue("ftrace_check_wq", WQ_UNBOUND, 0);
3780
3781         queue_work(ftrace_check_wq, &ftrace_check_work);
3782         return 0;
3783 }
3784
3785 static int __init ftrace_check_sync(void)
3786 {
3787         /* Make sure the ftrace_check updates are finished */
3788         if (ftrace_check_wq)
3789                 destroy_workqueue(ftrace_check_wq);
3790         return 0;
3791 }
3792
3793 late_initcall_sync(ftrace_check_sync);
3794 subsys_initcall(ftrace_check_for_weak_functions);
3795
3796 static int print_rec(struct seq_file *m, unsigned long ip)
3797 {
3798         unsigned long offset;
3799         char str[KSYM_SYMBOL_LEN];
3800         char *modname;
3801         const char *ret;
3802
3803         ret = kallsyms_lookup(ip, NULL, &offset, &modname, str);
3804         /* Weak functions can cause invalid addresses */
3805         if (!ret || offset > FTRACE_MCOUNT_MAX_OFFSET) {
3806                 snprintf(str, KSYM_SYMBOL_LEN, "%s_%ld",
3807                          FTRACE_INVALID_FUNCTION, offset);
3808                 ret = NULL;
3809         }
3810
3811         seq_puts(m, str);
3812         if (modname)
3813                 seq_printf(m, " [%s]", modname);
3814         return ret == NULL ? -1 : 0;
3815 }
3816 #else
3817 static inline int test_for_valid_rec(struct dyn_ftrace *rec)
3818 {
3819         return 1;
3820 }
3821
3822 static inline int print_rec(struct seq_file *m, unsigned long ip)
3823 {
3824         seq_printf(m, "%ps", (void *)ip);
3825         return 0;
3826 }
3827 #endif
3828
3829 static int t_show(struct seq_file *m, void *v)
3830 {
3831         struct ftrace_iterator *iter = m->private;
3832         struct dyn_ftrace *rec;
3833
3834         if (iter->flags & FTRACE_ITER_PROBE)
3835                 return t_probe_show(m, iter);
3836
3837         if (iter->flags & FTRACE_ITER_MOD)
3838                 return t_mod_show(m, iter);
3839
3840         if (iter->flags & FTRACE_ITER_PRINTALL) {
3841                 if (iter->flags & FTRACE_ITER_NOTRACE)
3842                         seq_puts(m, "#### no functions disabled ####\n");
3843                 else
3844                         seq_puts(m, "#### all functions enabled ####\n");
3845                 return 0;
3846         }
3847
3848         rec = iter->func;
3849
3850         if (!rec)
3851                 return 0;
3852
3853         if (print_rec(m, rec->ip)) {
3854                 /* This should only happen when a rec is disabled */
3855                 WARN_ON_ONCE(!(rec->flags & FTRACE_FL_DISABLED));
3856                 seq_putc(m, '\n');
3857                 return 0;
3858         }
3859
3860         if (iter->flags & FTRACE_ITER_ENABLED) {
3861                 struct ftrace_ops *ops;
3862
3863                 seq_printf(m, " (%ld)%s%s%s%s",
3864                            ftrace_rec_count(rec),
3865                            rec->flags & FTRACE_FL_REGS ? " R" : "  ",
3866                            rec->flags & FTRACE_FL_IPMODIFY ? " I" : "  ",
3867                            rec->flags & FTRACE_FL_DIRECT ? " D" : "  ",
3868                            rec->flags & FTRACE_FL_CALL_OPS ? " O" : "  ");
3869                 if (rec->flags & FTRACE_FL_TRAMP_EN) {
3870                         ops = ftrace_find_tramp_ops_any(rec);
3871                         if (ops) {
3872                                 do {
3873                                         seq_printf(m, "\ttramp: %pS (%pS)",
3874                                                    (void *)ops->trampoline,
3875                                                    (void *)ops->func);
3876                                         add_trampoline_func(m, ops, rec);
3877                                         ops = ftrace_find_tramp_ops_next(rec, ops);
3878                                 } while (ops);
3879                         } else
3880                                 seq_puts(m, "\ttramp: ERROR!");
3881                 } else {
3882                         add_trampoline_func(m, NULL, rec);
3883                 }
3884                 if (rec->flags & FTRACE_FL_CALL_OPS_EN) {
3885                         ops = ftrace_find_unique_ops(rec);
3886                         if (ops) {
3887                                 seq_printf(m, "\tops: %pS (%pS)",
3888                                            ops, ops->func);
3889                         } else {
3890                                 seq_puts(m, "\tops: ERROR!");
3891                         }
3892                 }
3893                 if (rec->flags & FTRACE_FL_DIRECT) {
3894                         unsigned long direct;
3895
3896                         direct = ftrace_find_rec_direct(rec->ip);
3897                         if (direct)
3898                                 seq_printf(m, "\n\tdirect-->%pS", (void *)direct);
3899                 }
3900         }
3901
3902         seq_putc(m, '\n');
3903
3904         return 0;
3905 }
3906
3907 static const struct seq_operations show_ftrace_seq_ops = {
3908         .start = t_start,
3909         .next = t_next,
3910         .stop = t_stop,
3911         .show = t_show,
3912 };
3913
3914 static int
3915 ftrace_avail_open(struct inode *inode, struct file *file)
3916 {
3917         struct ftrace_iterator *iter;
3918         int ret;
3919
3920         ret = security_locked_down(LOCKDOWN_TRACEFS);
3921         if (ret)
3922                 return ret;
3923
3924         if (unlikely(ftrace_disabled))
3925                 return -ENODEV;
3926
3927         iter = __seq_open_private(file, &show_ftrace_seq_ops, sizeof(*iter));
3928         if (!iter)
3929                 return -ENOMEM;
3930
3931         iter->pg = ftrace_pages_start;
3932         iter->ops = &global_ops;
3933
3934         return 0;
3935 }
3936
3937 static int
3938 ftrace_enabled_open(struct inode *inode, struct file *file)
3939 {
3940         struct ftrace_iterator *iter;
3941
3942         /*
3943          * This shows us what functions are currently being
3944          * traced and by what. Not sure if we want lockdown
3945          * to hide such critical information for an admin.
3946          * Although, perhaps it can show information we don't
3947          * want people to see, but if something is tracing
3948          * something, we probably want to know about it.
3949          */
3950
3951         iter = __seq_open_private(file, &show_ftrace_seq_ops, sizeof(*iter));
3952         if (!iter)
3953                 return -ENOMEM;
3954
3955         iter->pg = ftrace_pages_start;
3956         iter->flags = FTRACE_ITER_ENABLED;
3957         iter->ops = &global_ops;
3958
3959         return 0;
3960 }
3961
3962 /**
3963  * ftrace_regex_open - initialize function tracer filter files
3964  * @ops: The ftrace_ops that hold the hash filters
3965  * @flag: The type of filter to process
3966  * @inode: The inode, usually passed in to your open routine
3967  * @file: The file, usually passed in to your open routine
3968  *
3969  * ftrace_regex_open() initializes the filter files for the
3970  * @ops. Depending on @flag it may process the filter hash or
3971  * the notrace hash of @ops. With this called from the open
3972  * routine, you can use ftrace_filter_write() for the write
3973  * routine if @flag has FTRACE_ITER_FILTER set, or
3974  * ftrace_notrace_write() if @flag has FTRACE_ITER_NOTRACE set.
3975  * tracing_lseek() should be used as the lseek routine, and
3976  * release must call ftrace_regex_release().
3977  */
3978 int
3979 ftrace_regex_open(struct ftrace_ops *ops, int flag,
3980                   struct inode *inode, struct file *file)
3981 {
3982         struct ftrace_iterator *iter;
3983         struct ftrace_hash *hash;
3984         struct list_head *mod_head;
3985         struct trace_array *tr = ops->private;
3986         int ret = -ENOMEM;
3987
3988         ftrace_ops_init(ops);
3989
3990         if (unlikely(ftrace_disabled))
3991                 return -ENODEV;
3992
3993         if (tracing_check_open_get_tr(tr))
3994                 return -ENODEV;
3995
3996         iter = kzalloc(sizeof(*iter), GFP_KERNEL);
3997         if (!iter)
3998                 goto out;
3999
4000         if (trace_parser_get_init(&iter->parser, FTRACE_BUFF_MAX))
4001                 goto out;
4002
4003         iter->ops = ops;
4004         iter->flags = flag;
4005         iter->tr = tr;
4006
4007         mutex_lock(&ops->func_hash->regex_lock);
4008
4009         if (flag & FTRACE_ITER_NOTRACE) {
4010                 hash = ops->func_hash->notrace_hash;
4011                 mod_head = tr ? &tr->mod_notrace : NULL;
4012         } else {
4013                 hash = ops->func_hash->filter_hash;
4014                 mod_head = tr ? &tr->mod_trace : NULL;
4015         }
4016
4017         iter->mod_list = mod_head;
4018
4019         if (file->f_mode & FMODE_WRITE) {
4020                 const int size_bits = FTRACE_HASH_DEFAULT_BITS;
4021
4022                 if (file->f_flags & O_TRUNC) {
4023                         iter->hash = alloc_ftrace_hash(size_bits);
4024                         clear_ftrace_mod_list(mod_head);
4025                 } else {
4026                         iter->hash = alloc_and_copy_ftrace_hash(size_bits, hash);
4027                 }
4028
4029                 if (!iter->hash) {
4030                         trace_parser_put(&iter->parser);
4031                         goto out_unlock;
4032                 }
4033         } else
4034                 iter->hash = hash;
4035
4036         ret = 0;
4037
4038         if (file->f_mode & FMODE_READ) {
4039                 iter->pg = ftrace_pages_start;
4040
4041                 ret = seq_open(file, &show_ftrace_seq_ops);
4042                 if (!ret) {
4043                         struct seq_file *m = file->private_data;
4044                         m->private = iter;
4045                 } else {
4046                         /* Failed */
4047                         free_ftrace_hash(iter->hash);
4048                         trace_parser_put(&iter->parser);
4049                 }
4050         } else
4051                 file->private_data = iter;
4052
4053  out_unlock:
4054         mutex_unlock(&ops->func_hash->regex_lock);
4055
4056  out:
4057         if (ret) {
4058                 kfree(iter);
4059                 if (tr)
4060                         trace_array_put(tr);
4061         }
4062
4063         return ret;
4064 }
4065
4066 static int
4067 ftrace_filter_open(struct inode *inode, struct file *file)
4068 {
4069         struct ftrace_ops *ops = inode->i_private;
4070
4071         /* Checks for tracefs lockdown */
4072         return ftrace_regex_open(ops,
4073                         FTRACE_ITER_FILTER | FTRACE_ITER_DO_PROBES,
4074                         inode, file);
4075 }
4076
4077 static int
4078 ftrace_notrace_open(struct inode *inode, struct file *file)
4079 {
4080         struct ftrace_ops *ops = inode->i_private;
4081
4082         /* Checks for tracefs lockdown */
4083         return ftrace_regex_open(ops, FTRACE_ITER_NOTRACE,
4084                                  inode, file);
4085 }
4086
4087 /* Type for quick search ftrace basic regexes (globs) from filter_parse_regex */
4088 struct ftrace_glob {
4089         char *search;
4090         unsigned len;
4091         int type;
4092 };
4093
4094 /*
4095  * If symbols in an architecture don't correspond exactly to the user-visible
4096  * name of what they represent, it is possible to define this function to
4097  * perform the necessary adjustments.
4098 */
4099 char * __weak arch_ftrace_match_adjust(char *str, const char *search)
4100 {
4101         return str;
4102 }
4103
4104 static int ftrace_match(char *str, struct ftrace_glob *g)
4105 {
4106         int matched = 0;
4107         int slen;
4108
4109         str = arch_ftrace_match_adjust(str, g->search);
4110
4111         switch (g->type) {
4112         case MATCH_FULL:
4113                 if (strcmp(str, g->search) == 0)
4114                         matched = 1;
4115                 break;
4116         case MATCH_FRONT_ONLY:
4117                 if (strncmp(str, g->search, g->len) == 0)
4118                         matched = 1;
4119                 break;
4120         case MATCH_MIDDLE_ONLY:
4121                 if (strstr(str, g->search))
4122                         matched = 1;
4123                 break;
4124         case MATCH_END_ONLY:
4125                 slen = strlen(str);
4126                 if (slen >= g->len &&
4127                     memcmp(str + slen - g->len, g->search, g->len) == 0)
4128                         matched = 1;
4129                 break;
4130         case MATCH_GLOB:
4131                 if (glob_match(g->search, str))
4132                         matched = 1;
4133                 break;
4134         }
4135
4136         return matched;
4137 }
4138
4139 static int
4140 enter_record(struct ftrace_hash *hash, struct dyn_ftrace *rec, int clear_filter)
4141 {
4142         struct ftrace_func_entry *entry;
4143         int ret = 0;
4144
4145         entry = ftrace_lookup_ip(hash, rec->ip);
4146         if (clear_filter) {
4147                 /* Do nothing if it doesn't exist */
4148                 if (!entry)
4149                         return 0;
4150
4151                 free_hash_entry(hash, entry);
4152         } else {
4153                 /* Do nothing if it exists */
4154                 if (entry)
4155                         return 0;
4156
4157                 ret = add_hash_entry(hash, rec->ip);
4158         }
4159         return ret;
4160 }
4161
4162 static int
4163 add_rec_by_index(struct ftrace_hash *hash, struct ftrace_glob *func_g,
4164                  int clear_filter)
4165 {
4166         long index = simple_strtoul(func_g->search, NULL, 0);
4167         struct ftrace_page *pg;
4168         struct dyn_ftrace *rec;
4169
4170         /* The index starts at 1 */
4171         if (--index < 0)
4172                 return 0;
4173
4174         do_for_each_ftrace_rec(pg, rec) {
4175                 if (pg->index <= index) {
4176                         index -= pg->index;
4177                         /* this is a double loop, break goes to the next page */
4178                         break;
4179                 }
4180                 rec = &pg->records[index];
4181                 enter_record(hash, rec, clear_filter);
4182                 return 1;
4183         } while_for_each_ftrace_rec();
4184         return 0;
4185 }
4186
4187 #ifdef FTRACE_MCOUNT_MAX_OFFSET
4188 static int lookup_ip(unsigned long ip, char **modname, char *str)
4189 {
4190         unsigned long offset;
4191
4192         kallsyms_lookup(ip, NULL, &offset, modname, str);
4193         if (offset > FTRACE_MCOUNT_MAX_OFFSET)
4194                 return -1;
4195         return 0;
4196 }
4197 #else
4198 static int lookup_ip(unsigned long ip, char **modname, char *str)
4199 {
4200         kallsyms_lookup(ip, NULL, NULL, modname, str);
4201         return 0;
4202 }
4203 #endif
4204
4205 static int
4206 ftrace_match_record(struct dyn_ftrace *rec, struct ftrace_glob *func_g,
4207                 struct ftrace_glob *mod_g, int exclude_mod)
4208 {
4209         char str[KSYM_SYMBOL_LEN];
4210         char *modname;
4211
4212         if (lookup_ip(rec->ip, &modname, str)) {
4213                 /* This should only happen when a rec is disabled */
4214                 WARN_ON_ONCE(system_state == SYSTEM_RUNNING &&
4215                              !(rec->flags & FTRACE_FL_DISABLED));
4216                 return 0;
4217         }
4218
4219         if (mod_g) {
4220                 int mod_matches = (modname) ? ftrace_match(modname, mod_g) : 0;
4221
4222                 /* blank module name to match all modules */
4223                 if (!mod_g->len) {
4224                         /* blank module globbing: modname xor exclude_mod */
4225                         if (!exclude_mod != !modname)
4226                                 goto func_match;
4227                         return 0;
4228                 }
4229
4230                 /*
4231                  * exclude_mod is set to trace everything but the given
4232                  * module. If it is set and the module matches, then
4233                  * return 0. If it is not set, and the module doesn't match
4234                  * also return 0. Otherwise, check the function to see if
4235                  * that matches.
4236                  */
4237                 if (!mod_matches == !exclude_mod)
4238                         return 0;
4239 func_match:
4240                 /* blank search means to match all funcs in the mod */
4241                 if (!func_g->len)
4242                         return 1;
4243         }
4244
4245         return ftrace_match(str, func_g);
4246 }
4247
4248 static int
4249 match_records(struct ftrace_hash *hash, char *func, int len, char *mod)
4250 {
4251         struct ftrace_page *pg;
4252         struct dyn_ftrace *rec;
4253         struct ftrace_glob func_g = { .type = MATCH_FULL };
4254         struct ftrace_glob mod_g = { .type = MATCH_FULL };
4255         struct ftrace_glob *mod_match = (mod) ? &mod_g : NULL;
4256         int exclude_mod = 0;
4257         int found = 0;
4258         int ret;
4259         int clear_filter = 0;
4260
4261         if (func) {
4262                 func_g.type = filter_parse_regex(func, len, &func_g.search,
4263                                                  &clear_filter);
4264                 func_g.len = strlen(func_g.search);
4265         }
4266
4267         if (mod) {
4268                 mod_g.type = filter_parse_regex(mod, strlen(mod),
4269                                 &mod_g.search, &exclude_mod);
4270                 mod_g.len = strlen(mod_g.search);
4271         }
4272
4273         mutex_lock(&ftrace_lock);
4274
4275         if (unlikely(ftrace_disabled))
4276                 goto out_unlock;
4277
4278         if (func_g.type == MATCH_INDEX) {
4279                 found = add_rec_by_index(hash, &func_g, clear_filter);
4280                 goto out_unlock;
4281         }
4282
4283         do_for_each_ftrace_rec(pg, rec) {
4284
4285                 if (rec->flags & FTRACE_FL_DISABLED)
4286                         continue;
4287
4288                 if (ftrace_match_record(rec, &func_g, mod_match, exclude_mod)) {
4289                         ret = enter_record(hash, rec, clear_filter);
4290                         if (ret < 0) {
4291                                 found = ret;
4292                                 goto out_unlock;
4293                         }
4294                         found = 1;
4295                 }
4296                 cond_resched();
4297         } while_for_each_ftrace_rec();
4298  out_unlock:
4299         mutex_unlock(&ftrace_lock);
4300
4301         return found;
4302 }
4303
4304 static int
4305 ftrace_match_records(struct ftrace_hash *hash, char *buff, int len)
4306 {
4307         return match_records(hash, buff, len, NULL);
4308 }
4309
4310 static void ftrace_ops_update_code(struct ftrace_ops *ops,
4311                                    struct ftrace_ops_hash *old_hash)
4312 {
4313         struct ftrace_ops *op;
4314
4315         if (!ftrace_enabled)
4316                 return;
4317
4318         if (ops->flags & FTRACE_OPS_FL_ENABLED) {
4319                 ftrace_run_modify_code(ops, FTRACE_UPDATE_CALLS, old_hash);
4320                 return;
4321         }
4322
4323         /*
4324          * If this is the shared global_ops filter, then we need to
4325          * check if there is another ops that shares it, is enabled.
4326          * If so, we still need to run the modify code.
4327          */
4328         if (ops->func_hash != &global_ops.local_hash)
4329                 return;
4330
4331         do_for_each_ftrace_op(op, ftrace_ops_list) {
4332                 if (op->func_hash == &global_ops.local_hash &&
4333                     op->flags & FTRACE_OPS_FL_ENABLED) {
4334                         ftrace_run_modify_code(op, FTRACE_UPDATE_CALLS, old_hash);
4335                         /* Only need to do this once */
4336                         return;
4337                 }
4338         } while_for_each_ftrace_op(op);
4339 }
4340
4341 static int ftrace_hash_move_and_update_ops(struct ftrace_ops *ops,
4342                                            struct ftrace_hash **orig_hash,
4343                                            struct ftrace_hash *hash,
4344                                            int enable)
4345 {
4346         struct ftrace_ops_hash old_hash_ops;
4347         struct ftrace_hash *old_hash;
4348         int ret;
4349
4350         old_hash = *orig_hash;
4351         old_hash_ops.filter_hash = ops->func_hash->filter_hash;
4352         old_hash_ops.notrace_hash = ops->func_hash->notrace_hash;
4353         ret = ftrace_hash_move(ops, enable, orig_hash, hash);
4354         if (!ret) {
4355                 ftrace_ops_update_code(ops, &old_hash_ops);
4356                 free_ftrace_hash_rcu(old_hash);
4357         }
4358         return ret;
4359 }
4360
4361 static bool module_exists(const char *module)
4362 {
4363         /* All modules have the symbol __this_module */
4364         static const char this_mod[] = "__this_module";
4365         char modname[MAX_PARAM_PREFIX_LEN + sizeof(this_mod) + 2];
4366         unsigned long val;
4367         int n;
4368
4369         n = snprintf(modname, sizeof(modname), "%s:%s", module, this_mod);
4370
4371         if (n > sizeof(modname) - 1)
4372                 return false;
4373
4374         val = module_kallsyms_lookup_name(modname);
4375         return val != 0;
4376 }
4377
4378 static int cache_mod(struct trace_array *tr,
4379                      const char *func, char *module, int enable)
4380 {
4381         struct ftrace_mod_load *ftrace_mod, *n;
4382         struct list_head *head = enable ? &tr->mod_trace : &tr->mod_notrace;
4383         int ret;
4384
4385         mutex_lock(&ftrace_lock);
4386
4387         /* We do not cache inverse filters */
4388         if (func[0] == '!') {
4389                 func++;
4390                 ret = -EINVAL;
4391
4392                 /* Look to remove this hash */
4393                 list_for_each_entry_safe(ftrace_mod, n, head, list) {
4394                         if (strcmp(ftrace_mod->module, module) != 0)
4395                                 continue;
4396
4397                         /* no func matches all */
4398                         if (strcmp(func, "*") == 0 ||
4399                             (ftrace_mod->func &&
4400                              strcmp(ftrace_mod->func, func) == 0)) {
4401                                 ret = 0;
4402                                 free_ftrace_mod(ftrace_mod);
4403                                 continue;
4404                         }
4405                 }
4406                 goto out;
4407         }
4408
4409         ret = -EINVAL;
4410         /* We only care about modules that have not been loaded yet */
4411         if (module_exists(module))
4412                 goto out;
4413
4414         /* Save this string off, and execute it when the module is loaded */
4415         ret = ftrace_add_mod(tr, func, module, enable);
4416  out:
4417         mutex_unlock(&ftrace_lock);
4418
4419         return ret;
4420 }
4421
4422 static int
4423 ftrace_set_regex(struct ftrace_ops *ops, unsigned char *buf, int len,
4424                  int reset, int enable);
4425
4426 #ifdef CONFIG_MODULES
4427 static void process_mod_list(struct list_head *head, struct ftrace_ops *ops,
4428                              char *mod, bool enable)
4429 {
4430         struct ftrace_mod_load *ftrace_mod, *n;
4431         struct ftrace_hash **orig_hash, *new_hash;
4432         LIST_HEAD(process_mods);
4433         char *func;
4434
4435         mutex_lock(&ops->func_hash->regex_lock);
4436
4437         if (enable)
4438                 orig_hash = &ops->func_hash->filter_hash;
4439         else
4440                 orig_hash = &ops->func_hash->notrace_hash;
4441
4442         new_hash = alloc_and_copy_ftrace_hash(FTRACE_HASH_DEFAULT_BITS,
4443                                               *orig_hash);
4444         if (!new_hash)
4445                 goto out; /* warn? */
4446
4447         mutex_lock(&ftrace_lock);
4448
4449         list_for_each_entry_safe(ftrace_mod, n, head, list) {
4450
4451                 if (strcmp(ftrace_mod->module, mod) != 0)
4452                         continue;
4453
4454                 if (ftrace_mod->func)
4455                         func = kstrdup(ftrace_mod->func, GFP_KERNEL);
4456                 else
4457                         func = kstrdup("*", GFP_KERNEL);
4458
4459                 if (!func) /* warn? */
4460                         continue;
4461
4462                 list_move(&ftrace_mod->list, &process_mods);
4463
4464                 /* Use the newly allocated func, as it may be "*" */
4465                 kfree(ftrace_mod->func);
4466                 ftrace_mod->func = func;
4467         }
4468
4469         mutex_unlock(&ftrace_lock);
4470
4471         list_for_each_entry_safe(ftrace_mod, n, &process_mods, list) {
4472
4473                 func = ftrace_mod->func;
4474
4475                 /* Grabs ftrace_lock, which is why we have this extra step */
4476                 match_records(new_hash, func, strlen(func), mod);
4477                 free_ftrace_mod(ftrace_mod);
4478         }
4479
4480         if (enable && list_empty(head))
4481                 new_hash->flags &= ~FTRACE_HASH_FL_MOD;
4482
4483         mutex_lock(&ftrace_lock);
4484
4485         ftrace_hash_move_and_update_ops(ops, orig_hash,
4486                                               new_hash, enable);
4487         mutex_unlock(&ftrace_lock);
4488
4489  out:
4490         mutex_unlock(&ops->func_hash->regex_lock);
4491
4492         free_ftrace_hash(new_hash);
4493 }
4494
4495 static void process_cached_mods(const char *mod_name)
4496 {
4497         struct trace_array *tr;
4498         char *mod;
4499
4500         mod = kstrdup(mod_name, GFP_KERNEL);
4501         if (!mod)
4502                 return;
4503
4504         mutex_lock(&trace_types_lock);
4505         list_for_each_entry(tr, &ftrace_trace_arrays, list) {
4506                 if (!list_empty(&tr->mod_trace))
4507                         process_mod_list(&tr->mod_trace, tr->ops, mod, true);
4508                 if (!list_empty(&tr->mod_notrace))
4509                         process_mod_list(&tr->mod_notrace, tr->ops, mod, false);
4510         }
4511         mutex_unlock(&trace_types_lock);
4512
4513         kfree(mod);
4514 }
4515 #endif
4516
4517 /*
4518  * We register the module command as a template to show others how
4519  * to register the a command as well.
4520  */
4521
4522 static int
4523 ftrace_mod_callback(struct trace_array *tr, struct ftrace_hash *hash,
4524                     char *func_orig, char *cmd, char *module, int enable)
4525 {
4526         char *func;
4527         int ret;
4528
4529         /* match_records() modifies func, and we need the original */
4530         func = kstrdup(func_orig, GFP_KERNEL);
4531         if (!func)
4532                 return -ENOMEM;
4533
4534         /*
4535          * cmd == 'mod' because we only registered this func
4536          * for the 'mod' ftrace_func_command.
4537          * But if you register one func with multiple commands,
4538          * you can tell which command was used by the cmd
4539          * parameter.
4540          */
4541         ret = match_records(hash, func, strlen(func), module);
4542         kfree(func);
4543
4544         if (!ret)
4545                 return cache_mod(tr, func_orig, module, enable);
4546         if (ret < 0)
4547                 return ret;
4548         return 0;
4549 }
4550
4551 static struct ftrace_func_command ftrace_mod_cmd = {
4552         .name                   = "mod",
4553         .func                   = ftrace_mod_callback,
4554 };
4555
4556 static int __init ftrace_mod_cmd_init(void)
4557 {
4558         return register_ftrace_command(&ftrace_mod_cmd);
4559 }
4560 core_initcall(ftrace_mod_cmd_init);
4561
4562 static void function_trace_probe_call(unsigned long ip, unsigned long parent_ip,
4563                                       struct ftrace_ops *op, struct ftrace_regs *fregs)
4564 {
4565         struct ftrace_probe_ops *probe_ops;
4566         struct ftrace_func_probe *probe;
4567
4568         probe = container_of(op, struct ftrace_func_probe, ops);
4569         probe_ops = probe->probe_ops;
4570
4571         /*
4572          * Disable preemption for these calls to prevent a RCU grace
4573          * period. This syncs the hash iteration and freeing of items
4574          * on the hash. rcu_read_lock is too dangerous here.
4575          */
4576         preempt_disable_notrace();
4577         probe_ops->func(ip, parent_ip, probe->tr, probe_ops, probe->data);
4578         preempt_enable_notrace();
4579 }
4580
4581 struct ftrace_func_map {
4582         struct ftrace_func_entry        entry;
4583         void                            *data;
4584 };
4585
4586 struct ftrace_func_mapper {
4587         struct ftrace_hash              hash;
4588 };
4589
4590 /**
4591  * allocate_ftrace_func_mapper - allocate a new ftrace_func_mapper
4592  *
4593  * Returns a ftrace_func_mapper descriptor that can be used to map ips to data.
4594  */
4595 struct ftrace_func_mapper *allocate_ftrace_func_mapper(void)
4596 {
4597         struct ftrace_hash *hash;
4598
4599         /*
4600          * The mapper is simply a ftrace_hash, but since the entries
4601          * in the hash are not ftrace_func_entry type, we define it
4602          * as a separate structure.
4603          */
4604         hash = alloc_ftrace_hash(FTRACE_HASH_DEFAULT_BITS);
4605         return (struct ftrace_func_mapper *)hash;
4606 }
4607
4608 /**
4609  * ftrace_func_mapper_find_ip - Find some data mapped to an ip
4610  * @mapper: The mapper that has the ip maps
4611  * @ip: the instruction pointer to find the data for
4612  *
4613  * Returns the data mapped to @ip if found otherwise NULL. The return
4614  * is actually the address of the mapper data pointer. The address is
4615  * returned for use cases where the data is no bigger than a long, and
4616  * the user can use the data pointer as its data instead of having to
4617  * allocate more memory for the reference.
4618  */
4619 void **ftrace_func_mapper_find_ip(struct ftrace_func_mapper *mapper,
4620                                   unsigned long ip)
4621 {
4622         struct ftrace_func_entry *entry;
4623         struct ftrace_func_map *map;
4624
4625         entry = ftrace_lookup_ip(&mapper->hash, ip);
4626         if (!entry)
4627                 return NULL;
4628
4629         map = (struct ftrace_func_map *)entry;
4630         return &map->data;
4631 }
4632
4633 /**
4634  * ftrace_func_mapper_add_ip - Map some data to an ip
4635  * @mapper: The mapper that has the ip maps
4636  * @ip: The instruction pointer address to map @data to
4637  * @data: The data to map to @ip
4638  *
4639  * Returns 0 on success otherwise an error.
4640  */
4641 int ftrace_func_mapper_add_ip(struct ftrace_func_mapper *mapper,
4642                               unsigned long ip, void *data)
4643 {
4644         struct ftrace_func_entry *entry;
4645         struct ftrace_func_map *map;
4646
4647         entry = ftrace_lookup_ip(&mapper->hash, ip);
4648         if (entry)
4649                 return -EBUSY;
4650
4651         map = kmalloc(sizeof(*map), GFP_KERNEL);
4652         if (!map)
4653                 return -ENOMEM;
4654
4655         map->entry.ip = ip;
4656         map->data = data;
4657
4658         __add_hash_entry(&mapper->hash, &map->entry);
4659
4660         return 0;
4661 }
4662
4663 /**
4664  * ftrace_func_mapper_remove_ip - Remove an ip from the mapping
4665  * @mapper: The mapper that has the ip maps
4666  * @ip: The instruction pointer address to remove the data from
4667  *
4668  * Returns the data if it is found, otherwise NULL.
4669  * Note, if the data pointer is used as the data itself, (see
4670  * ftrace_func_mapper_find_ip(), then the return value may be meaningless,
4671  * if the data pointer was set to zero.
4672  */
4673 void *ftrace_func_mapper_remove_ip(struct ftrace_func_mapper *mapper,
4674                                    unsigned long ip)
4675 {
4676         struct ftrace_func_entry *entry;
4677         struct ftrace_func_map *map;
4678         void *data;
4679
4680         entry = ftrace_lookup_ip(&mapper->hash, ip);
4681         if (!entry)
4682                 return NULL;
4683
4684         map = (struct ftrace_func_map *)entry;
4685         data = map->data;
4686
4687         remove_hash_entry(&mapper->hash, entry);
4688         kfree(entry);
4689
4690         return data;
4691 }
4692
4693 /**
4694  * free_ftrace_func_mapper - free a mapping of ips and data
4695  * @mapper: The mapper that has the ip maps
4696  * @free_func: A function to be called on each data item.
4697  *
4698  * This is used to free the function mapper. The @free_func is optional
4699  * and can be used if the data needs to be freed as well.
4700  */
4701 void free_ftrace_func_mapper(struct ftrace_func_mapper *mapper,
4702                              ftrace_mapper_func free_func)
4703 {
4704         struct ftrace_func_entry *entry;
4705         struct ftrace_func_map *map;
4706         struct hlist_head *hhd;
4707         int size, i;
4708
4709         if (!mapper)
4710                 return;
4711
4712         if (free_func && mapper->hash.count) {
4713                 size = 1 << mapper->hash.size_bits;
4714                 for (i = 0; i < size; i++) {
4715                         hhd = &mapper->hash.buckets[i];
4716                         hlist_for_each_entry(entry, hhd, hlist) {
4717                                 map = (struct ftrace_func_map *)entry;
4718                                 free_func(map);
4719                         }
4720                 }
4721         }
4722         free_ftrace_hash(&mapper->hash);
4723 }
4724
4725 static void release_probe(struct ftrace_func_probe *probe)
4726 {
4727         struct ftrace_probe_ops *probe_ops;
4728
4729         mutex_lock(&ftrace_lock);
4730
4731         WARN_ON(probe->ref <= 0);
4732
4733         /* Subtract the ref that was used to protect this instance */
4734         probe->ref--;
4735
4736         if (!probe->ref) {
4737                 probe_ops = probe->probe_ops;
4738                 /*
4739                  * Sending zero as ip tells probe_ops to free
4740                  * the probe->data itself
4741                  */
4742                 if (probe_ops->free)
4743                         probe_ops->free(probe_ops, probe->tr, 0, probe->data);
4744                 list_del(&probe->list);
4745                 kfree(probe);
4746         }
4747         mutex_unlock(&ftrace_lock);
4748 }
4749
4750 static void acquire_probe_locked(struct ftrace_func_probe *probe)
4751 {
4752         /*
4753          * Add one ref to keep it from being freed when releasing the
4754          * ftrace_lock mutex.
4755          */
4756         probe->ref++;
4757 }
4758
4759 int
4760 register_ftrace_function_probe(char *glob, struct trace_array *tr,
4761                                struct ftrace_probe_ops *probe_ops,
4762                                void *data)
4763 {
4764         struct ftrace_func_probe *probe = NULL, *iter;
4765         struct ftrace_func_entry *entry;
4766         struct ftrace_hash **orig_hash;
4767         struct ftrace_hash *old_hash;
4768         struct ftrace_hash *hash;
4769         int count = 0;
4770         int size;
4771         int ret;
4772         int i;
4773
4774         if (WARN_ON(!tr))
4775                 return -EINVAL;
4776
4777         /* We do not support '!' for function probes */
4778         if (WARN_ON(glob[0] == '!'))
4779                 return -EINVAL;
4780
4781
4782         mutex_lock(&ftrace_lock);
4783         /* Check if the probe_ops is already registered */
4784         list_for_each_entry(iter, &tr->func_probes, list) {
4785                 if (iter->probe_ops == probe_ops) {
4786                         probe = iter;
4787                         break;
4788                 }
4789         }
4790         if (!probe) {
4791                 probe = kzalloc(sizeof(*probe), GFP_KERNEL);
4792                 if (!probe) {
4793                         mutex_unlock(&ftrace_lock);
4794                         return -ENOMEM;
4795                 }
4796                 probe->probe_ops = probe_ops;
4797                 probe->ops.func = function_trace_probe_call;
4798                 probe->tr = tr;
4799                 ftrace_ops_init(&probe->ops);
4800                 list_add(&probe->list, &tr->func_probes);
4801         }
4802
4803         acquire_probe_locked(probe);
4804
4805         mutex_unlock(&ftrace_lock);
4806
4807         /*
4808          * Note, there's a small window here that the func_hash->filter_hash
4809          * may be NULL or empty. Need to be careful when reading the loop.
4810          */
4811         mutex_lock(&probe->ops.func_hash->regex_lock);
4812
4813         orig_hash = &probe->ops.func_hash->filter_hash;
4814         old_hash = *orig_hash;
4815         hash = alloc_and_copy_ftrace_hash(FTRACE_HASH_DEFAULT_BITS, old_hash);
4816
4817         if (!hash) {
4818                 ret = -ENOMEM;
4819                 goto out;
4820         }
4821
4822         ret = ftrace_match_records(hash, glob, strlen(glob));
4823
4824         /* Nothing found? */
4825         if (!ret)
4826                 ret = -EINVAL;
4827
4828         if (ret < 0)
4829                 goto out;
4830
4831         size = 1 << hash->size_bits;
4832         for (i = 0; i < size; i++) {
4833                 hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
4834                         if (ftrace_lookup_ip(old_hash, entry->ip))
4835                                 continue;
4836                         /*
4837                          * The caller might want to do something special
4838                          * for each function we find. We call the callback
4839                          * to give the caller an opportunity to do so.
4840                          */
4841                         if (probe_ops->init) {
4842                                 ret = probe_ops->init(probe_ops, tr,
4843                                                       entry->ip, data,
4844                                                       &probe->data);
4845                                 if (ret < 0) {
4846                                         if (probe_ops->free && count)
4847                                                 probe_ops->free(probe_ops, tr,
4848                                                                 0, probe->data);
4849                                         probe->data = NULL;
4850                                         goto out;
4851                                 }
4852                         }
4853                         count++;
4854                 }
4855         }
4856
4857         mutex_lock(&ftrace_lock);
4858
4859         if (!count) {
4860                 /* Nothing was added? */
4861                 ret = -EINVAL;
4862                 goto out_unlock;
4863         }
4864
4865         ret = ftrace_hash_move_and_update_ops(&probe->ops, orig_hash,
4866                                               hash, 1);
4867         if (ret < 0)
4868                 goto err_unlock;
4869
4870         /* One ref for each new function traced */
4871         probe->ref += count;
4872
4873         if (!(probe->ops.flags & FTRACE_OPS_FL_ENABLED))
4874                 ret = ftrace_startup(&probe->ops, 0);
4875
4876  out_unlock:
4877         mutex_unlock(&ftrace_lock);
4878
4879         if (!ret)
4880                 ret = count;
4881  out:
4882         mutex_unlock(&probe->ops.func_hash->regex_lock);
4883         free_ftrace_hash(hash);
4884
4885         release_probe(probe);
4886
4887         return ret;
4888
4889  err_unlock:
4890         if (!probe_ops->free || !count)
4891                 goto out_unlock;
4892
4893         /* Failed to do the move, need to call the free functions */
4894         for (i = 0; i < size; i++) {
4895                 hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
4896                         if (ftrace_lookup_ip(old_hash, entry->ip))
4897                                 continue;
4898                         probe_ops->free(probe_ops, tr, entry->ip, probe->data);
4899                 }
4900         }
4901         goto out_unlock;
4902 }
4903
4904 int
4905 unregister_ftrace_function_probe_func(char *glob, struct trace_array *tr,
4906                                       struct ftrace_probe_ops *probe_ops)
4907 {
4908         struct ftrace_func_probe *probe = NULL, *iter;
4909         struct ftrace_ops_hash old_hash_ops;
4910         struct ftrace_func_entry *entry;
4911         struct ftrace_glob func_g;
4912         struct ftrace_hash **orig_hash;
4913         struct ftrace_hash *old_hash;
4914         struct ftrace_hash *hash = NULL;
4915         struct hlist_node *tmp;
4916         struct hlist_head hhd;
4917         char str[KSYM_SYMBOL_LEN];
4918         int count = 0;
4919         int i, ret = -ENODEV;
4920         int size;
4921
4922         if (!glob || !strlen(glob) || !strcmp(glob, "*"))
4923                 func_g.search = NULL;
4924         else {
4925                 int not;
4926
4927                 func_g.type = filter_parse_regex(glob, strlen(glob),
4928                                                  &func_g.search, &not);
4929                 func_g.len = strlen(func_g.search);
4930
4931                 /* we do not support '!' for function probes */
4932                 if (WARN_ON(not))
4933                         return -EINVAL;
4934         }
4935
4936         mutex_lock(&ftrace_lock);
4937         /* Check if the probe_ops is already registered */
4938         list_for_each_entry(iter, &tr->func_probes, list) {
4939                 if (iter->probe_ops == probe_ops) {
4940                         probe = iter;
4941                         break;
4942                 }
4943         }
4944         if (!probe)
4945                 goto err_unlock_ftrace;
4946
4947         ret = -EINVAL;
4948         if (!(probe->ops.flags & FTRACE_OPS_FL_INITIALIZED))
4949                 goto err_unlock_ftrace;
4950
4951         acquire_probe_locked(probe);
4952
4953         mutex_unlock(&ftrace_lock);
4954
4955         mutex_lock(&probe->ops.func_hash->regex_lock);
4956
4957         orig_hash = &probe->ops.func_hash->filter_hash;
4958         old_hash = *orig_hash;
4959
4960         if (ftrace_hash_empty(old_hash))
4961                 goto out_unlock;
4962
4963         old_hash_ops.filter_hash = old_hash;
4964         /* Probes only have filters */
4965         old_hash_ops.notrace_hash = NULL;
4966
4967         ret = -ENOMEM;
4968         hash = alloc_and_copy_ftrace_hash(FTRACE_HASH_DEFAULT_BITS, old_hash);
4969         if (!hash)
4970                 goto out_unlock;
4971
4972         INIT_HLIST_HEAD(&hhd);
4973
4974         size = 1 << hash->size_bits;
4975         for (i = 0; i < size; i++) {
4976                 hlist_for_each_entry_safe(entry, tmp, &hash->buckets[i], hlist) {
4977
4978                         if (func_g.search) {
4979                                 kallsyms_lookup(entry->ip, NULL, NULL,
4980                                                 NULL, str);
4981                                 if (!ftrace_match(str, &func_g))
4982                                         continue;
4983                         }
4984                         count++;
4985                         remove_hash_entry(hash, entry);
4986                         hlist_add_head(&entry->hlist, &hhd);
4987                 }
4988         }
4989
4990         /* Nothing found? */
4991         if (!count) {
4992                 ret = -EINVAL;
4993                 goto out_unlock;
4994         }
4995
4996         mutex_lock(&ftrace_lock);
4997
4998         WARN_ON(probe->ref < count);
4999
5000         probe->ref -= count;
5001
5002         if (ftrace_hash_empty(hash))
5003                 ftrace_shutdown(&probe->ops, 0);
5004
5005         ret = ftrace_hash_move_and_update_ops(&probe->ops, orig_hash,
5006                                               hash, 1);
5007
5008         /* still need to update the function call sites */
5009         if (ftrace_enabled && !ftrace_hash_empty(hash))
5010                 ftrace_run_modify_code(&probe->ops, FTRACE_UPDATE_CALLS,
5011                                        &old_hash_ops);
5012         synchronize_rcu();
5013
5014         hlist_for_each_entry_safe(entry, tmp, &hhd, hlist) {
5015                 hlist_del(&entry->hlist);
5016                 if (probe_ops->free)
5017                         probe_ops->free(probe_ops, tr, entry->ip, probe->data);
5018                 kfree(entry);
5019         }
5020         mutex_unlock(&ftrace_lock);
5021
5022  out_unlock:
5023         mutex_unlock(&probe->ops.func_hash->regex_lock);
5024         free_ftrace_hash(hash);
5025
5026         release_probe(probe);
5027
5028         return ret;
5029
5030  err_unlock_ftrace:
5031         mutex_unlock(&ftrace_lock);
5032         return ret;
5033 }
5034
5035 void clear_ftrace_function_probes(struct trace_array *tr)
5036 {
5037         struct ftrace_func_probe *probe, *n;
5038
5039         list_for_each_entry_safe(probe, n, &tr->func_probes, list)
5040                 unregister_ftrace_function_probe_func(NULL, tr, probe->probe_ops);
5041 }
5042
5043 static LIST_HEAD(ftrace_commands);
5044 static DEFINE_MUTEX(ftrace_cmd_mutex);
5045
5046 /*
5047  * Currently we only register ftrace commands from __init, so mark this
5048  * __init too.
5049  */
5050 __init int register_ftrace_command(struct ftrace_func_command *cmd)
5051 {
5052         struct ftrace_func_command *p;
5053         int ret = 0;
5054
5055         mutex_lock(&ftrace_cmd_mutex);
5056         list_for_each_entry(p, &ftrace_commands, list) {
5057                 if (strcmp(cmd->name, p->name) == 0) {
5058                         ret = -EBUSY;
5059                         goto out_unlock;
5060                 }
5061         }
5062         list_add(&cmd->list, &ftrace_commands);
5063  out_unlock:
5064         mutex_unlock(&ftrace_cmd_mutex);
5065
5066         return ret;
5067 }
5068
5069 /*
5070  * Currently we only unregister ftrace commands from __init, so mark
5071  * this __init too.
5072  */
5073 __init int unregister_ftrace_command(struct ftrace_func_command *cmd)
5074 {
5075         struct ftrace_func_command *p, *n;
5076         int ret = -ENODEV;
5077
5078         mutex_lock(&ftrace_cmd_mutex);
5079         list_for_each_entry_safe(p, n, &ftrace_commands, list) {
5080                 if (strcmp(cmd->name, p->name) == 0) {
5081                         ret = 0;
5082                         list_del_init(&p->list);
5083                         goto out_unlock;
5084                 }
5085         }
5086  out_unlock:
5087         mutex_unlock(&ftrace_cmd_mutex);
5088
5089         return ret;
5090 }
5091
5092 static int ftrace_process_regex(struct ftrace_iterator *iter,
5093                                 char *buff, int len, int enable)
5094 {
5095         struct ftrace_hash *hash = iter->hash;
5096         struct trace_array *tr = iter->ops->private;
5097         char *func, *command, *next = buff;
5098         struct ftrace_func_command *p;
5099         int ret = -EINVAL;
5100
5101         func = strsep(&next, ":");
5102
5103         if (!next) {
5104                 ret = ftrace_match_records(hash, func, len);
5105                 if (!ret)
5106                         ret = -EINVAL;
5107                 if (ret < 0)
5108                         return ret;
5109                 return 0;
5110         }
5111
5112         /* command found */
5113
5114         command = strsep(&next, ":");
5115
5116         mutex_lock(&ftrace_cmd_mutex);
5117         list_for_each_entry(p, &ftrace_commands, list) {
5118                 if (strcmp(p->name, command) == 0) {
5119                         ret = p->func(tr, hash, func, command, next, enable);
5120                         goto out_unlock;
5121                 }
5122         }
5123  out_unlock:
5124         mutex_unlock(&ftrace_cmd_mutex);
5125
5126         return ret;
5127 }
5128
5129 static ssize_t
5130 ftrace_regex_write(struct file *file, const char __user *ubuf,
5131                    size_t cnt, loff_t *ppos, int enable)
5132 {
5133         struct ftrace_iterator *iter;
5134         struct trace_parser *parser;
5135         ssize_t ret, read;
5136
5137         if (!cnt)
5138                 return 0;
5139
5140         if (file->f_mode & FMODE_READ) {
5141                 struct seq_file *m = file->private_data;
5142                 iter = m->private;
5143         } else
5144                 iter = file->private_data;
5145
5146         if (unlikely(ftrace_disabled))
5147                 return -ENODEV;
5148
5149         /* iter->hash is a local copy, so we don't need regex_lock */
5150
5151         parser = &iter->parser;
5152         read = trace_get_user(parser, ubuf, cnt, ppos);
5153
5154         if (read >= 0 && trace_parser_loaded(parser) &&
5155             !trace_parser_cont(parser)) {
5156                 ret = ftrace_process_regex(iter, parser->buffer,
5157                                            parser->idx, enable);
5158                 trace_parser_clear(parser);
5159                 if (ret < 0)
5160                         goto out;
5161         }
5162
5163         ret = read;
5164  out:
5165         return ret;
5166 }
5167
5168 ssize_t
5169 ftrace_filter_write(struct file *file, const char __user *ubuf,
5170                     size_t cnt, loff_t *ppos)
5171 {
5172         return ftrace_regex_write(file, ubuf, cnt, ppos, 1);
5173 }
5174
5175 ssize_t
5176 ftrace_notrace_write(struct file *file, const char __user *ubuf,
5177                      size_t cnt, loff_t *ppos)
5178 {
5179         return ftrace_regex_write(file, ubuf, cnt, ppos, 0);
5180 }
5181
5182 static int
5183 __ftrace_match_addr(struct ftrace_hash *hash, unsigned long ip, int remove)
5184 {
5185         struct ftrace_func_entry *entry;
5186
5187         ip = ftrace_location(ip);
5188         if (!ip)
5189                 return -EINVAL;
5190
5191         if (remove) {
5192                 entry = ftrace_lookup_ip(hash, ip);
5193                 if (!entry)
5194                         return -ENOENT;
5195                 free_hash_entry(hash, entry);
5196                 return 0;
5197         }
5198
5199         return add_hash_entry(hash, ip);
5200 }
5201
5202 static int
5203 ftrace_match_addr(struct ftrace_hash *hash, unsigned long *ips,
5204                   unsigned int cnt, int remove)
5205 {
5206         unsigned int i;
5207         int err;
5208
5209         for (i = 0; i < cnt; i++) {
5210                 err = __ftrace_match_addr(hash, ips[i], remove);
5211                 if (err) {
5212                         /*
5213                          * This expects the @hash is a temporary hash and if this
5214                          * fails the caller must free the @hash.
5215                          */
5216                         return err;
5217                 }
5218         }
5219         return 0;
5220 }
5221
5222 static int
5223 ftrace_set_hash(struct ftrace_ops *ops, unsigned char *buf, int len,
5224                 unsigned long *ips, unsigned int cnt,
5225                 int remove, int reset, int enable)
5226 {
5227         struct ftrace_hash **orig_hash;
5228         struct ftrace_hash *hash;
5229         int ret;
5230
5231         if (unlikely(ftrace_disabled))
5232                 return -ENODEV;
5233
5234         mutex_lock(&ops->func_hash->regex_lock);
5235
5236         if (enable)
5237                 orig_hash = &ops->func_hash->filter_hash;
5238         else
5239                 orig_hash = &ops->func_hash->notrace_hash;
5240
5241         if (reset)
5242                 hash = alloc_ftrace_hash(FTRACE_HASH_DEFAULT_BITS);
5243         else
5244                 hash = alloc_and_copy_ftrace_hash(FTRACE_HASH_DEFAULT_BITS, *orig_hash);
5245
5246         if (!hash) {
5247                 ret = -ENOMEM;
5248                 goto out_regex_unlock;
5249         }
5250
5251         if (buf && !ftrace_match_records(hash, buf, len)) {
5252                 ret = -EINVAL;
5253                 goto out_regex_unlock;
5254         }
5255         if (ips) {
5256                 ret = ftrace_match_addr(hash, ips, cnt, remove);
5257                 if (ret < 0)
5258                         goto out_regex_unlock;
5259         }
5260
5261         mutex_lock(&ftrace_lock);
5262         ret = ftrace_hash_move_and_update_ops(ops, orig_hash, hash, enable);
5263         mutex_unlock(&ftrace_lock);
5264
5265  out_regex_unlock:
5266         mutex_unlock(&ops->func_hash->regex_lock);
5267
5268         free_ftrace_hash(hash);
5269         return ret;
5270 }
5271
5272 static int
5273 ftrace_set_addr(struct ftrace_ops *ops, unsigned long *ips, unsigned int cnt,
5274                 int remove, int reset, int enable)
5275 {
5276         return ftrace_set_hash(ops, NULL, 0, ips, cnt, remove, reset, enable);
5277 }
5278
5279 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
5280
5281 struct ftrace_direct_func {
5282         struct list_head        next;
5283         unsigned long           addr;
5284         int                     count;
5285 };
5286
5287 static LIST_HEAD(ftrace_direct_funcs);
5288
5289 static int register_ftrace_function_nolock(struct ftrace_ops *ops);
5290
5291 #define MULTI_FLAGS (FTRACE_OPS_FL_DIRECT | FTRACE_OPS_FL_SAVE_ARGS)
5292
5293 static int check_direct_multi(struct ftrace_ops *ops)
5294 {
5295         if (!(ops->flags & FTRACE_OPS_FL_INITIALIZED))
5296                 return -EINVAL;
5297         if ((ops->flags & MULTI_FLAGS) != MULTI_FLAGS)
5298                 return -EINVAL;
5299         return 0;
5300 }
5301
5302 static void remove_direct_functions_hash(struct ftrace_hash *hash, unsigned long addr)
5303 {
5304         struct ftrace_func_entry *entry, *del;
5305         int size, i;
5306
5307         size = 1 << hash->size_bits;
5308         for (i = 0; i < size; i++) {
5309                 hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
5310                         del = __ftrace_lookup_ip(direct_functions, entry->ip);
5311                         if (del && del->direct == addr) {
5312                                 remove_hash_entry(direct_functions, del);
5313                                 kfree(del);
5314                         }
5315                 }
5316         }
5317 }
5318
5319 /**
5320  * register_ftrace_direct - Call a custom trampoline directly
5321  * for multiple functions registered in @ops
5322  * @ops: The address of the struct ftrace_ops object
5323  * @addr: The address of the trampoline to call at @ops functions
5324  *
5325  * This is used to connect a direct calls to @addr from the nop locations
5326  * of the functions registered in @ops (with by ftrace_set_filter_ip
5327  * function).
5328  *
5329  * The location that it calls (@addr) must be able to handle a direct call,
5330  * and save the parameters of the function being traced, and restore them
5331  * (or inject new ones if needed), before returning.
5332  *
5333  * Returns:
5334  *  0 on success
5335  *  -EINVAL  - The @ops object was already registered with this call or
5336  *             when there are no functions in @ops object.
5337  *  -EBUSY   - Another direct function is already attached (there can be only one)
5338  *  -ENODEV  - @ip does not point to a ftrace nop location (or not supported)
5339  *  -ENOMEM  - There was an allocation failure.
5340  */
5341 int register_ftrace_direct(struct ftrace_ops *ops, unsigned long addr)
5342 {
5343         struct ftrace_hash *hash, *free_hash = NULL;
5344         struct ftrace_func_entry *entry, *new;
5345         int err = -EBUSY, size, i;
5346
5347         if (ops->func || ops->trampoline)
5348                 return -EINVAL;
5349         if (!(ops->flags & FTRACE_OPS_FL_INITIALIZED))
5350                 return -EINVAL;
5351         if (ops->flags & FTRACE_OPS_FL_ENABLED)
5352                 return -EINVAL;
5353
5354         hash = ops->func_hash->filter_hash;
5355         if (ftrace_hash_empty(hash))
5356                 return -EINVAL;
5357
5358         mutex_lock(&direct_mutex);
5359
5360         /* Make sure requested entries are not already registered.. */
5361         size = 1 << hash->size_bits;
5362         for (i = 0; i < size; i++) {
5363                 hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
5364                         if (ftrace_find_rec_direct(entry->ip))
5365                                 goto out_unlock;
5366                 }
5367         }
5368
5369         /* ... and insert them to direct_functions hash. */
5370         err = -ENOMEM;
5371         for (i = 0; i < size; i++) {
5372                 hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
5373                         new = ftrace_add_rec_direct(entry->ip, addr, &free_hash);
5374                         if (!new)
5375                                 goto out_remove;
5376                         entry->direct = addr;
5377                 }
5378         }
5379
5380         ops->func = call_direct_funcs;
5381         ops->flags = MULTI_FLAGS;
5382         ops->trampoline = FTRACE_REGS_ADDR;
5383         ops->direct_call = addr;
5384
5385         err = register_ftrace_function_nolock(ops);
5386
5387  out_remove:
5388         if (err)
5389                 remove_direct_functions_hash(hash, addr);
5390
5391  out_unlock:
5392         mutex_unlock(&direct_mutex);
5393
5394         if (free_hash) {
5395                 synchronize_rcu_tasks();
5396                 free_ftrace_hash(free_hash);
5397         }
5398         return err;
5399 }
5400 EXPORT_SYMBOL_GPL(register_ftrace_direct);
5401
5402 /**
5403  * unregister_ftrace_direct - Remove calls to custom trampoline
5404  * previously registered by register_ftrace_direct for @ops object.
5405  * @ops: The address of the struct ftrace_ops object
5406  *
5407  * This is used to remove a direct calls to @addr from the nop locations
5408  * of the functions registered in @ops (with by ftrace_set_filter_ip
5409  * function).
5410  *
5411  * Returns:
5412  *  0 on success
5413  *  -EINVAL - The @ops object was not properly registered.
5414  */
5415 int unregister_ftrace_direct(struct ftrace_ops *ops, unsigned long addr,
5416                              bool free_filters)
5417 {
5418         struct ftrace_hash *hash = ops->func_hash->filter_hash;
5419         int err;
5420
5421         if (check_direct_multi(ops))
5422                 return -EINVAL;
5423         if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
5424                 return -EINVAL;
5425
5426         mutex_lock(&direct_mutex);
5427         err = unregister_ftrace_function(ops);
5428         remove_direct_functions_hash(hash, addr);
5429         mutex_unlock(&direct_mutex);
5430
5431         /* cleanup for possible another register call */
5432         ops->func = NULL;
5433         ops->trampoline = 0;
5434
5435         if (free_filters)
5436                 ftrace_free_filter(ops);
5437         return err;
5438 }
5439 EXPORT_SYMBOL_GPL(unregister_ftrace_direct);
5440
5441 static int
5442 __modify_ftrace_direct(struct ftrace_ops *ops, unsigned long addr)
5443 {
5444         struct ftrace_hash *hash;
5445         struct ftrace_func_entry *entry, *iter;
5446         static struct ftrace_ops tmp_ops = {
5447                 .func           = ftrace_stub,
5448                 .flags          = FTRACE_OPS_FL_STUB,
5449         };
5450         int i, size;
5451         int err;
5452
5453         lockdep_assert_held_once(&direct_mutex);
5454
5455         /* Enable the tmp_ops to have the same functions as the direct ops */
5456         ftrace_ops_init(&tmp_ops);
5457         tmp_ops.func_hash = ops->func_hash;
5458         tmp_ops.direct_call = addr;
5459
5460         err = register_ftrace_function_nolock(&tmp_ops);
5461         if (err)
5462                 return err;
5463
5464         /*
5465          * Now the ftrace_ops_list_func() is called to do the direct callers.
5466          * We can safely change the direct functions attached to each entry.
5467          */
5468         mutex_lock(&ftrace_lock);
5469
5470         hash = ops->func_hash->filter_hash;
5471         size = 1 << hash->size_bits;
5472         for (i = 0; i < size; i++) {
5473                 hlist_for_each_entry(iter, &hash->buckets[i], hlist) {
5474                         entry = __ftrace_lookup_ip(direct_functions, iter->ip);
5475                         if (!entry)
5476                                 continue;
5477                         entry->direct = addr;
5478                 }
5479         }
5480         /* Prevent store tearing if a trampoline concurrently accesses the value */
5481         WRITE_ONCE(ops->direct_call, addr);
5482
5483         mutex_unlock(&ftrace_lock);
5484
5485         /* Removing the tmp_ops will add the updated direct callers to the functions */
5486         unregister_ftrace_function(&tmp_ops);
5487
5488         return err;
5489 }
5490
5491 /**
5492  * modify_ftrace_direct_nolock - Modify an existing direct 'multi' call
5493  * to call something else
5494  * @ops: The address of the struct ftrace_ops object
5495  * @addr: The address of the new trampoline to call at @ops functions
5496  *
5497  * This is used to unregister currently registered direct caller and
5498  * register new one @addr on functions registered in @ops object.
5499  *
5500  * Note there's window between ftrace_shutdown and ftrace_startup calls
5501  * where there will be no callbacks called.
5502  *
5503  * Caller should already have direct_mutex locked, so we don't lock
5504  * direct_mutex here.
5505  *
5506  * Returns: zero on success. Non zero on error, which includes:
5507  *  -EINVAL - The @ops object was not properly registered.
5508  */
5509 int modify_ftrace_direct_nolock(struct ftrace_ops *ops, unsigned long addr)
5510 {
5511         if (check_direct_multi(ops))
5512                 return -EINVAL;
5513         if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
5514                 return -EINVAL;
5515
5516         return __modify_ftrace_direct(ops, addr);
5517 }
5518 EXPORT_SYMBOL_GPL(modify_ftrace_direct_nolock);
5519
5520 /**
5521  * modify_ftrace_direct - Modify an existing direct 'multi' call
5522  * to call something else
5523  * @ops: The address of the struct ftrace_ops object
5524  * @addr: The address of the new trampoline to call at @ops functions
5525  *
5526  * This is used to unregister currently registered direct caller and
5527  * register new one @addr on functions registered in @ops object.
5528  *
5529  * Note there's window between ftrace_shutdown and ftrace_startup calls
5530  * where there will be no callbacks called.
5531  *
5532  * Returns: zero on success. Non zero on error, which includes:
5533  *  -EINVAL - The @ops object was not properly registered.
5534  */
5535 int modify_ftrace_direct(struct ftrace_ops *ops, unsigned long addr)
5536 {
5537         int err;
5538
5539         if (check_direct_multi(ops))
5540                 return -EINVAL;
5541         if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
5542                 return -EINVAL;
5543
5544         mutex_lock(&direct_mutex);
5545         err = __modify_ftrace_direct(ops, addr);
5546         mutex_unlock(&direct_mutex);
5547         return err;
5548 }
5549 EXPORT_SYMBOL_GPL(modify_ftrace_direct);
5550 #endif /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS */
5551
5552 /**
5553  * ftrace_set_filter_ip - set a function to filter on in ftrace by address
5554  * @ops - the ops to set the filter with
5555  * @ip - the address to add to or remove from the filter.
5556  * @remove - non zero to remove the ip from the filter
5557  * @reset - non zero to reset all filters before applying this filter.
5558  *
5559  * Filters denote which functions should be enabled when tracing is enabled
5560  * If @ip is NULL, it fails to update filter.
5561  *
5562  * This can allocate memory which must be freed before @ops can be freed,
5563  * either by removing each filtered addr or by using
5564  * ftrace_free_filter(@ops).
5565  */
5566 int ftrace_set_filter_ip(struct ftrace_ops *ops, unsigned long ip,
5567                          int remove, int reset)
5568 {
5569         ftrace_ops_init(ops);
5570         return ftrace_set_addr(ops, &ip, 1, remove, reset, 1);
5571 }
5572 EXPORT_SYMBOL_GPL(ftrace_set_filter_ip);
5573
5574 /**
5575  * ftrace_set_filter_ips - set functions to filter on in ftrace by addresses
5576  * @ops - the ops to set the filter with
5577  * @ips - the array of addresses to add to or remove from the filter.
5578  * @cnt - the number of addresses in @ips
5579  * @remove - non zero to remove ips from the filter
5580  * @reset - non zero to reset all filters before applying this filter.
5581  *
5582  * Filters denote which functions should be enabled when tracing is enabled
5583  * If @ips array or any ip specified within is NULL , it fails to update filter.
5584  *
5585  * This can allocate memory which must be freed before @ops can be freed,
5586  * either by removing each filtered addr or by using
5587  * ftrace_free_filter(@ops).
5588 */
5589 int ftrace_set_filter_ips(struct ftrace_ops *ops, unsigned long *ips,
5590                           unsigned int cnt, int remove, int reset)
5591 {
5592         ftrace_ops_init(ops);
5593         return ftrace_set_addr(ops, ips, cnt, remove, reset, 1);
5594 }
5595 EXPORT_SYMBOL_GPL(ftrace_set_filter_ips);
5596
5597 /**
5598  * ftrace_ops_set_global_filter - setup ops to use global filters
5599  * @ops - the ops which will use the global filters
5600  *
5601  * ftrace users who need global function trace filtering should call this.
5602  * It can set the global filter only if ops were not initialized before.
5603  */
5604 void ftrace_ops_set_global_filter(struct ftrace_ops *ops)
5605 {
5606         if (ops->flags & FTRACE_OPS_FL_INITIALIZED)
5607                 return;
5608
5609         ftrace_ops_init(ops);
5610         ops->func_hash = &global_ops.local_hash;
5611 }
5612 EXPORT_SYMBOL_GPL(ftrace_ops_set_global_filter);
5613
5614 static int
5615 ftrace_set_regex(struct ftrace_ops *ops, unsigned char *buf, int len,
5616                  int reset, int enable)
5617 {
5618         return ftrace_set_hash(ops, buf, len, NULL, 0, 0, reset, enable);
5619 }
5620
5621 /**
5622  * ftrace_set_filter - set a function to filter on in ftrace
5623  * @ops - the ops to set the filter with
5624  * @buf - the string that holds the function filter text.
5625  * @len - the length of the string.
5626  * @reset - non zero to reset all filters before applying this filter.
5627  *
5628  * Filters denote which functions should be enabled when tracing is enabled.
5629  * If @buf is NULL and reset is set, all functions will be enabled for tracing.
5630  *
5631  * This can allocate memory which must be freed before @ops can be freed,
5632  * either by removing each filtered addr or by using
5633  * ftrace_free_filter(@ops).
5634  */
5635 int ftrace_set_filter(struct ftrace_ops *ops, unsigned char *buf,
5636                        int len, int reset)
5637 {
5638         ftrace_ops_init(ops);
5639         return ftrace_set_regex(ops, buf, len, reset, 1);
5640 }
5641 EXPORT_SYMBOL_GPL(ftrace_set_filter);
5642
5643 /**
5644  * ftrace_set_notrace - set a function to not trace in ftrace
5645  * @ops - the ops to set the notrace filter with
5646  * @buf - the string that holds the function notrace text.
5647  * @len - the length of the string.
5648  * @reset - non zero to reset all filters before applying this filter.
5649  *
5650  * Notrace Filters denote which functions should not be enabled when tracing
5651  * is enabled. If @buf is NULL and reset is set, all functions will be enabled
5652  * for tracing.
5653  *
5654  * This can allocate memory which must be freed before @ops can be freed,
5655  * either by removing each filtered addr or by using
5656  * ftrace_free_filter(@ops).
5657  */
5658 int ftrace_set_notrace(struct ftrace_ops *ops, unsigned char *buf,
5659                         int len, int reset)
5660 {
5661         ftrace_ops_init(ops);
5662         return ftrace_set_regex(ops, buf, len, reset, 0);
5663 }
5664 EXPORT_SYMBOL_GPL(ftrace_set_notrace);
5665 /**
5666  * ftrace_set_global_filter - set a function to filter on with global tracers
5667  * @buf - the string that holds the function filter text.
5668  * @len - the length of the string.
5669  * @reset - non zero to reset all filters before applying this filter.
5670  *
5671  * Filters denote which functions should be enabled when tracing is enabled.
5672  * If @buf is NULL and reset is set, all functions will be enabled for tracing.
5673  */
5674 void ftrace_set_global_filter(unsigned char *buf, int len, int reset)
5675 {
5676         ftrace_set_regex(&global_ops, buf, len, reset, 1);
5677 }
5678 EXPORT_SYMBOL_GPL(ftrace_set_global_filter);
5679
5680 /**
5681  * ftrace_set_global_notrace - set a function to not trace with global tracers
5682  * @buf - the string that holds the function notrace text.
5683  * @len - the length of the string.
5684  * @reset - non zero to reset all filters before applying this filter.
5685  *
5686  * Notrace Filters denote which functions should not be enabled when tracing
5687  * is enabled. If @buf is NULL and reset is set, all functions will be enabled
5688  * for tracing.
5689  */
5690 void ftrace_set_global_notrace(unsigned char *buf, int len, int reset)
5691 {
5692         ftrace_set_regex(&global_ops, buf, len, reset, 0);
5693 }
5694 EXPORT_SYMBOL_GPL(ftrace_set_global_notrace);
5695
5696 /*
5697  * command line interface to allow users to set filters on boot up.
5698  */
5699 #define FTRACE_FILTER_SIZE              COMMAND_LINE_SIZE
5700 static char ftrace_notrace_buf[FTRACE_FILTER_SIZE] __initdata;
5701 static char ftrace_filter_buf[FTRACE_FILTER_SIZE] __initdata;
5702
5703 /* Used by function selftest to not test if filter is set */
5704 bool ftrace_filter_param __initdata;
5705
5706 static int __init set_ftrace_notrace(char *str)
5707 {
5708         ftrace_filter_param = true;
5709         strlcpy(ftrace_notrace_buf, str, FTRACE_FILTER_SIZE);
5710         return 1;
5711 }
5712 __setup("ftrace_notrace=", set_ftrace_notrace);
5713
5714 static int __init set_ftrace_filter(char *str)
5715 {
5716         ftrace_filter_param = true;
5717         strlcpy(ftrace_filter_buf, str, FTRACE_FILTER_SIZE);
5718         return 1;
5719 }
5720 __setup("ftrace_filter=", set_ftrace_filter);
5721
5722 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
5723 static char ftrace_graph_buf[FTRACE_FILTER_SIZE] __initdata;
5724 static char ftrace_graph_notrace_buf[FTRACE_FILTER_SIZE] __initdata;
5725 static int ftrace_graph_set_hash(struct ftrace_hash *hash, char *buffer);
5726
5727 static int __init set_graph_function(char *str)
5728 {
5729         strlcpy(ftrace_graph_buf, str, FTRACE_FILTER_SIZE);
5730         return 1;
5731 }
5732 __setup("ftrace_graph_filter=", set_graph_function);
5733
5734 static int __init set_graph_notrace_function(char *str)
5735 {
5736         strlcpy(ftrace_graph_notrace_buf, str, FTRACE_FILTER_SIZE);
5737         return 1;
5738 }
5739 __setup("ftrace_graph_notrace=", set_graph_notrace_function);
5740
5741 static int __init set_graph_max_depth_function(char *str)
5742 {
5743         if (!str)
5744                 return 0;
5745         fgraph_max_depth = simple_strtoul(str, NULL, 0);
5746         return 1;
5747 }
5748 __setup("ftrace_graph_max_depth=", set_graph_max_depth_function);
5749
5750 static void __init set_ftrace_early_graph(char *buf, int enable)
5751 {
5752         int ret;
5753         char *func;
5754         struct ftrace_hash *hash;
5755
5756         hash = alloc_ftrace_hash(FTRACE_HASH_DEFAULT_BITS);
5757         if (MEM_FAIL(!hash, "Failed to allocate hash\n"))
5758                 return;
5759
5760         while (buf) {
5761                 func = strsep(&buf, ",");
5762                 /* we allow only one expression at a time */
5763                 ret = ftrace_graph_set_hash(hash, func);
5764                 if (ret)
5765                         printk(KERN_DEBUG "ftrace: function %s not "
5766                                           "traceable\n", func);
5767         }
5768
5769         if (enable)
5770                 ftrace_graph_hash = hash;
5771         else
5772                 ftrace_graph_notrace_hash = hash;
5773 }
5774 #endif /* CONFIG_FUNCTION_GRAPH_TRACER */
5775
5776 void __init
5777 ftrace_set_early_filter(struct ftrace_ops *ops, char *buf, int enable)
5778 {
5779         char *func;
5780
5781         ftrace_ops_init(ops);
5782
5783         while (buf) {
5784                 func = strsep(&buf, ",");
5785                 ftrace_set_regex(ops, func, strlen(func), 0, enable);
5786         }
5787 }
5788
5789 static void __init set_ftrace_early_filters(void)
5790 {
5791         if (ftrace_filter_buf[0])
5792                 ftrace_set_early_filter(&global_ops, ftrace_filter_buf, 1);
5793         if (ftrace_notrace_buf[0])
5794                 ftrace_set_early_filter(&global_ops, ftrace_notrace_buf, 0);
5795 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
5796         if (ftrace_graph_buf[0])
5797                 set_ftrace_early_graph(ftrace_graph_buf, 1);
5798         if (ftrace_graph_notrace_buf[0])
5799                 set_ftrace_early_graph(ftrace_graph_notrace_buf, 0);
5800 #endif /* CONFIG_FUNCTION_GRAPH_TRACER */
5801 }
5802
5803 int ftrace_regex_release(struct inode *inode, struct file *file)
5804 {
5805         struct seq_file *m = (struct seq_file *)file->private_data;
5806         struct ftrace_iterator *iter;
5807         struct ftrace_hash **orig_hash;
5808         struct trace_parser *parser;
5809         int filter_hash;
5810
5811         if (file->f_mode & FMODE_READ) {
5812                 iter = m->private;
5813                 seq_release(inode, file);
5814         } else
5815                 iter = file->private_data;
5816
5817         parser = &iter->parser;
5818         if (trace_parser_loaded(parser)) {
5819                 int enable = !(iter->flags & FTRACE_ITER_NOTRACE);
5820
5821                 ftrace_process_regex(iter, parser->buffer,
5822                                      parser->idx, enable);
5823         }
5824
5825         trace_parser_put(parser);
5826
5827         mutex_lock(&iter->ops->func_hash->regex_lock);
5828
5829         if (file->f_mode & FMODE_WRITE) {
5830                 filter_hash = !!(iter->flags & FTRACE_ITER_FILTER);
5831
5832                 if (filter_hash) {
5833                         orig_hash = &iter->ops->func_hash->filter_hash;
5834                         if (iter->tr) {
5835                                 if (list_empty(&iter->tr->mod_trace))
5836                                         iter->hash->flags &= ~FTRACE_HASH_FL_MOD;
5837                                 else
5838                                         iter->hash->flags |= FTRACE_HASH_FL_MOD;
5839                         }
5840                 } else
5841                         orig_hash = &iter->ops->func_hash->notrace_hash;
5842
5843                 mutex_lock(&ftrace_lock);
5844                 ftrace_hash_move_and_update_ops(iter->ops, orig_hash,
5845                                                       iter->hash, filter_hash);
5846                 mutex_unlock(&ftrace_lock);
5847         } else {
5848                 /* For read only, the hash is the ops hash */
5849                 iter->hash = NULL;
5850         }
5851
5852         mutex_unlock(&iter->ops->func_hash->regex_lock);
5853         free_ftrace_hash(iter->hash);
5854         if (iter->tr)
5855                 trace_array_put(iter->tr);
5856         kfree(iter);
5857
5858         return 0;
5859 }
5860
5861 static const struct file_operations ftrace_avail_fops = {
5862         .open = ftrace_avail_open,
5863         .read = seq_read,
5864         .llseek = seq_lseek,
5865         .release = seq_release_private,
5866 };
5867
5868 static const struct file_operations ftrace_enabled_fops = {
5869         .open = ftrace_enabled_open,
5870         .read = seq_read,
5871         .llseek = seq_lseek,
5872         .release = seq_release_private,
5873 };
5874
5875 static const struct file_operations ftrace_filter_fops = {
5876         .open = ftrace_filter_open,
5877         .read = seq_read,
5878         .write = ftrace_filter_write,
5879         .llseek = tracing_lseek,
5880         .release = ftrace_regex_release,
5881 };
5882
5883 static const struct file_operations ftrace_notrace_fops = {
5884         .open = ftrace_notrace_open,
5885         .read = seq_read,
5886         .write = ftrace_notrace_write,
5887         .llseek = tracing_lseek,
5888         .release = ftrace_regex_release,
5889 };
5890
5891 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
5892
5893 static DEFINE_MUTEX(graph_lock);
5894
5895 struct ftrace_hash __rcu *ftrace_graph_hash = EMPTY_HASH;
5896 struct ftrace_hash __rcu *ftrace_graph_notrace_hash = EMPTY_HASH;
5897
5898 enum graph_filter_type {
5899         GRAPH_FILTER_NOTRACE    = 0,
5900         GRAPH_FILTER_FUNCTION,
5901 };
5902
5903 #define FTRACE_GRAPH_EMPTY      ((void *)1)
5904
5905 struct ftrace_graph_data {
5906         struct ftrace_hash              *hash;
5907         struct ftrace_func_entry        *entry;
5908         int                             idx;   /* for hash table iteration */
5909         enum graph_filter_type          type;
5910         struct ftrace_hash              *new_hash;
5911         const struct seq_operations     *seq_ops;
5912         struct trace_parser             parser;
5913 };
5914
5915 static void *
5916 __g_next(struct seq_file *m, loff_t *pos)
5917 {
5918         struct ftrace_graph_data *fgd = m->private;
5919         struct ftrace_func_entry *entry = fgd->entry;
5920         struct hlist_head *head;
5921         int i, idx = fgd->idx;
5922
5923         if (*pos >= fgd->hash->count)
5924                 return NULL;
5925
5926         if (entry) {
5927                 hlist_for_each_entry_continue(entry, hlist) {
5928                         fgd->entry = entry;
5929                         return entry;
5930                 }
5931
5932                 idx++;
5933         }
5934
5935         for (i = idx; i < 1 << fgd->hash->size_bits; i++) {
5936                 head = &fgd->hash->buckets[i];
5937                 hlist_for_each_entry(entry, head, hlist) {
5938                         fgd->entry = entry;
5939                         fgd->idx = i;
5940                         return entry;
5941                 }
5942         }
5943         return NULL;
5944 }
5945
5946 static void *
5947 g_next(struct seq_file *m, void *v, loff_t *pos)
5948 {
5949         (*pos)++;
5950         return __g_next(m, pos);
5951 }
5952
5953 static void *g_start(struct seq_file *m, loff_t *pos)
5954 {
5955         struct ftrace_graph_data *fgd = m->private;
5956
5957         mutex_lock(&graph_lock);
5958
5959         if (fgd->type == GRAPH_FILTER_FUNCTION)
5960                 fgd->hash = rcu_dereference_protected(ftrace_graph_hash,
5961                                         lockdep_is_held(&graph_lock));
5962         else
5963                 fgd->hash = rcu_dereference_protected(ftrace_graph_notrace_hash,
5964                                         lockdep_is_held(&graph_lock));
5965
5966         /* Nothing, tell g_show to print all functions are enabled */
5967         if (ftrace_hash_empty(fgd->hash) && !*pos)
5968                 return FTRACE_GRAPH_EMPTY;
5969
5970         fgd->idx = 0;
5971         fgd->entry = NULL;
5972         return __g_next(m, pos);
5973 }
5974
5975 static void g_stop(struct seq_file *m, void *p)
5976 {
5977         mutex_unlock(&graph_lock);
5978 }
5979
5980 static int g_show(struct seq_file *m, void *v)
5981 {
5982         struct ftrace_func_entry *entry = v;
5983
5984         if (!entry)
5985                 return 0;
5986
5987         if (entry == FTRACE_GRAPH_EMPTY) {
5988                 struct ftrace_graph_data *fgd = m->private;
5989
5990                 if (fgd->type == GRAPH_FILTER_FUNCTION)
5991                         seq_puts(m, "#### all functions enabled ####\n");
5992                 else
5993                         seq_puts(m, "#### no functions disabled ####\n");
5994                 return 0;
5995         }
5996
5997         seq_printf(m, "%ps\n", (void *)entry->ip);
5998
5999         return 0;
6000 }
6001
6002 static const struct seq_operations ftrace_graph_seq_ops = {
6003         .start = g_start,
6004         .next = g_next,
6005         .stop = g_stop,
6006         .show = g_show,
6007 };
6008
6009 static int
6010 __ftrace_graph_open(struct inode *inode, struct file *file,
6011                     struct ftrace_graph_data *fgd)
6012 {
6013         int ret;
6014         struct ftrace_hash *new_hash = NULL;
6015
6016         ret = security_locked_down(LOCKDOWN_TRACEFS);
6017         if (ret)
6018                 return ret;
6019
6020         if (file->f_mode & FMODE_WRITE) {
6021                 const int size_bits = FTRACE_HASH_DEFAULT_BITS;
6022
6023                 if (trace_parser_get_init(&fgd->parser, FTRACE_BUFF_MAX))
6024                         return -ENOMEM;
6025
6026                 if (file->f_flags & O_TRUNC)
6027                         new_hash = alloc_ftrace_hash(size_bits);
6028                 else
6029                         new_hash = alloc_and_copy_ftrace_hash(size_bits,
6030                                                               fgd->hash);
6031                 if (!new_hash) {
6032                         ret = -ENOMEM;
6033                         goto out;
6034                 }
6035         }
6036
6037         if (file->f_mode & FMODE_READ) {
6038                 ret = seq_open(file, &ftrace_graph_seq_ops);
6039                 if (!ret) {
6040                         struct seq_file *m = file->private_data;
6041                         m->private = fgd;
6042                 } else {
6043                         /* Failed */
6044                         free_ftrace_hash(new_hash);
6045                         new_hash = NULL;
6046                 }
6047         } else
6048                 file->private_data = fgd;
6049
6050 out:
6051         if (ret < 0 && file->f_mode & FMODE_WRITE)
6052                 trace_parser_put(&fgd->parser);
6053
6054         fgd->new_hash = new_hash;
6055
6056         /*
6057          * All uses of fgd->hash must be taken with the graph_lock
6058          * held. The graph_lock is going to be released, so force
6059          * fgd->hash to be reinitialized when it is taken again.
6060          */
6061         fgd->hash = NULL;
6062
6063         return ret;
6064 }
6065
6066 static int
6067 ftrace_graph_open(struct inode *inode, struct file *file)
6068 {
6069         struct ftrace_graph_data *fgd;
6070         int ret;
6071
6072         if (unlikely(ftrace_disabled))
6073                 return -ENODEV;
6074
6075         fgd = kmalloc(sizeof(*fgd), GFP_KERNEL);
6076         if (fgd == NULL)
6077                 return -ENOMEM;
6078
6079         mutex_lock(&graph_lock);
6080
6081         fgd->hash = rcu_dereference_protected(ftrace_graph_hash,
6082                                         lockdep_is_held(&graph_lock));
6083         fgd->type = GRAPH_FILTER_FUNCTION;
6084         fgd->seq_ops = &ftrace_graph_seq_ops;
6085
6086         ret = __ftrace_graph_open(inode, file, fgd);
6087         if (ret < 0)
6088                 kfree(fgd);
6089
6090         mutex_unlock(&graph_lock);
6091         return ret;
6092 }
6093
6094 static int
6095 ftrace_graph_notrace_open(struct inode *inode, struct file *file)
6096 {
6097         struct ftrace_graph_data *fgd;
6098         int ret;
6099
6100         if (unlikely(ftrace_disabled))
6101                 return -ENODEV;
6102
6103         fgd = kmalloc(sizeof(*fgd), GFP_KERNEL);
6104         if (fgd == NULL)
6105                 return -ENOMEM;
6106
6107         mutex_lock(&graph_lock);
6108
6109         fgd->hash = rcu_dereference_protected(ftrace_graph_notrace_hash,
6110                                         lockdep_is_held(&graph_lock));
6111         fgd->type = GRAPH_FILTER_NOTRACE;
6112         fgd->seq_ops = &ftrace_graph_seq_ops;
6113
6114         ret = __ftrace_graph_open(inode, file, fgd);
6115         if (ret < 0)
6116                 kfree(fgd);
6117
6118         mutex_unlock(&graph_lock);
6119         return ret;
6120 }
6121
6122 static int
6123 ftrace_graph_release(struct inode *inode, struct file *file)
6124 {
6125         struct ftrace_graph_data *fgd;
6126         struct ftrace_hash *old_hash, *new_hash;
6127         struct trace_parser *parser;
6128         int ret = 0;
6129
6130         if (file->f_mode & FMODE_READ) {
6131                 struct seq_file *m = file->private_data;
6132
6133                 fgd = m->private;
6134                 seq_release(inode, file);
6135         } else {
6136                 fgd = file->private_data;
6137         }
6138
6139
6140         if (file->f_mode & FMODE_WRITE) {
6141
6142                 parser = &fgd->parser;
6143
6144                 if (trace_parser_loaded((parser))) {
6145                         ret = ftrace_graph_set_hash(fgd->new_hash,
6146                                                     parser->buffer);
6147                 }
6148
6149                 trace_parser_put(parser);
6150
6151                 new_hash = __ftrace_hash_move(fgd->new_hash);
6152                 if (!new_hash) {
6153                         ret = -ENOMEM;
6154                         goto out;
6155                 }
6156
6157                 mutex_lock(&graph_lock);
6158
6159                 if (fgd->type == GRAPH_FILTER_FUNCTION) {
6160                         old_hash = rcu_dereference_protected(ftrace_graph_hash,
6161                                         lockdep_is_held(&graph_lock));
6162                         rcu_assign_pointer(ftrace_graph_hash, new_hash);
6163                 } else {
6164                         old_hash = rcu_dereference_protected(ftrace_graph_notrace_hash,
6165                                         lockdep_is_held(&graph_lock));
6166                         rcu_assign_pointer(ftrace_graph_notrace_hash, new_hash);
6167                 }
6168
6169                 mutex_unlock(&graph_lock);
6170
6171                 /*
6172                  * We need to do a hard force of sched synchronization.
6173                  * This is because we use preempt_disable() to do RCU, but
6174                  * the function tracers can be called where RCU is not watching
6175                  * (like before user_exit()). We can not rely on the RCU
6176                  * infrastructure to do the synchronization, thus we must do it
6177                  * ourselves.
6178                  */
6179                 if (old_hash != EMPTY_HASH)
6180                         synchronize_rcu_tasks_rude();
6181
6182                 free_ftrace_hash(old_hash);
6183         }
6184
6185  out:
6186         free_ftrace_hash(fgd->new_hash);
6187         kfree(fgd);
6188
6189         return ret;
6190 }
6191
6192 static int
6193 ftrace_graph_set_hash(struct ftrace_hash *hash, char *buffer)
6194 {
6195         struct ftrace_glob func_g;
6196         struct dyn_ftrace *rec;
6197         struct ftrace_page *pg;
6198         struct ftrace_func_entry *entry;
6199         int fail = 1;
6200         int not;
6201
6202         /* decode regex */
6203         func_g.type = filter_parse_regex(buffer, strlen(buffer),
6204                                          &func_g.search, &not);
6205
6206         func_g.len = strlen(func_g.search);
6207
6208         mutex_lock(&ftrace_lock);
6209
6210         if (unlikely(ftrace_disabled)) {
6211                 mutex_unlock(&ftrace_lock);
6212                 return -ENODEV;
6213         }
6214
6215         do_for_each_ftrace_rec(pg, rec) {
6216
6217                 if (rec->flags & FTRACE_FL_DISABLED)
6218                         continue;
6219
6220                 if (ftrace_match_record(rec, &func_g, NULL, 0)) {
6221                         entry = ftrace_lookup_ip(hash, rec->ip);
6222
6223                         if (!not) {
6224                                 fail = 0;
6225
6226                                 if (entry)
6227                                         continue;
6228                                 if (add_hash_entry(hash, rec->ip) < 0)
6229                                         goto out;
6230                         } else {
6231                                 if (entry) {
6232                                         free_hash_entry(hash, entry);
6233                                         fail = 0;
6234                                 }
6235                         }
6236                 }
6237         } while_for_each_ftrace_rec();
6238 out:
6239         mutex_unlock(&ftrace_lock);
6240
6241         if (fail)
6242                 return -EINVAL;
6243
6244         return 0;
6245 }
6246
6247 static ssize_t
6248 ftrace_graph_write(struct file *file, const char __user *ubuf,
6249                    size_t cnt, loff_t *ppos)
6250 {
6251         ssize_t read, ret = 0;
6252         struct ftrace_graph_data *fgd = file->private_data;
6253         struct trace_parser *parser;
6254
6255         if (!cnt)
6256                 return 0;
6257
6258         /* Read mode uses seq functions */
6259         if (file->f_mode & FMODE_READ) {
6260                 struct seq_file *m = file->private_data;
6261                 fgd = m->private;
6262         }
6263
6264         parser = &fgd->parser;
6265
6266         read = trace_get_user(parser, ubuf, cnt, ppos);
6267
6268         if (read >= 0 && trace_parser_loaded(parser) &&
6269             !trace_parser_cont(parser)) {
6270
6271                 ret = ftrace_graph_set_hash(fgd->new_hash,
6272                                             parser->buffer);
6273                 trace_parser_clear(parser);
6274         }
6275
6276         if (!ret)
6277                 ret = read;
6278
6279         return ret;
6280 }
6281
6282 static const struct file_operations ftrace_graph_fops = {
6283         .open           = ftrace_graph_open,
6284         .read           = seq_read,
6285         .write          = ftrace_graph_write,
6286         .llseek         = tracing_lseek,
6287         .release        = ftrace_graph_release,
6288 };
6289
6290 static const struct file_operations ftrace_graph_notrace_fops = {
6291         .open           = ftrace_graph_notrace_open,
6292         .read           = seq_read,
6293         .write          = ftrace_graph_write,
6294         .llseek         = tracing_lseek,
6295         .release        = ftrace_graph_release,
6296 };
6297 #endif /* CONFIG_FUNCTION_GRAPH_TRACER */
6298
6299 void ftrace_create_filter_files(struct ftrace_ops *ops,
6300                                 struct dentry *parent)
6301 {
6302
6303         trace_create_file("set_ftrace_filter", TRACE_MODE_WRITE, parent,
6304                           ops, &ftrace_filter_fops);
6305
6306         trace_create_file("set_ftrace_notrace", TRACE_MODE_WRITE, parent,
6307                           ops, &ftrace_notrace_fops);
6308 }
6309
6310 /*
6311  * The name "destroy_filter_files" is really a misnomer. Although
6312  * in the future, it may actually delete the files, but this is
6313  * really intended to make sure the ops passed in are disabled
6314  * and that when this function returns, the caller is free to
6315  * free the ops.
6316  *
6317  * The "destroy" name is only to match the "create" name that this
6318  * should be paired with.
6319  */
6320 void ftrace_destroy_filter_files(struct ftrace_ops *ops)
6321 {
6322         mutex_lock(&ftrace_lock);
6323         if (ops->flags & FTRACE_OPS_FL_ENABLED)
6324                 ftrace_shutdown(ops, 0);
6325         ops->flags |= FTRACE_OPS_FL_DELETED;
6326         ftrace_free_filter(ops);
6327         mutex_unlock(&ftrace_lock);
6328 }
6329
6330 static __init int ftrace_init_dyn_tracefs(struct dentry *d_tracer)
6331 {
6332
6333         trace_create_file("available_filter_functions", TRACE_MODE_READ,
6334                         d_tracer, NULL, &ftrace_avail_fops);
6335
6336         trace_create_file("enabled_functions", TRACE_MODE_READ,
6337                         d_tracer, NULL, &ftrace_enabled_fops);
6338
6339         ftrace_create_filter_files(&global_ops, d_tracer);
6340
6341 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
6342         trace_create_file("set_graph_function", TRACE_MODE_WRITE, d_tracer,
6343                                     NULL,
6344                                     &ftrace_graph_fops);
6345         trace_create_file("set_graph_notrace", TRACE_MODE_WRITE, d_tracer,
6346                                     NULL,
6347                                     &ftrace_graph_notrace_fops);
6348 #endif /* CONFIG_FUNCTION_GRAPH_TRACER */
6349
6350         return 0;
6351 }
6352
6353 static int ftrace_cmp_ips(const void *a, const void *b)
6354 {
6355         const unsigned long *ipa = a;
6356         const unsigned long *ipb = b;
6357
6358         if (*ipa > *ipb)
6359                 return 1;
6360         if (*ipa < *ipb)
6361                 return -1;
6362         return 0;
6363 }
6364
6365 #ifdef CONFIG_FTRACE_SORT_STARTUP_TEST
6366 static void test_is_sorted(unsigned long *start, unsigned long count)
6367 {
6368         int i;
6369
6370         for (i = 1; i < count; i++) {
6371                 if (WARN(start[i - 1] > start[i],
6372                          "[%d] %pS at %lx is not sorted with %pS at %lx\n", i,
6373                          (void *)start[i - 1], start[i - 1],
6374                          (void *)start[i], start[i]))
6375                         break;
6376         }
6377         if (i == count)
6378                 pr_info("ftrace section at %px sorted properly\n", start);
6379 }
6380 #else
6381 static void test_is_sorted(unsigned long *start, unsigned long count)
6382 {
6383 }
6384 #endif
6385
6386 static int ftrace_process_locs(struct module *mod,
6387                                unsigned long *start,
6388                                unsigned long *end)
6389 {
6390         struct ftrace_page *start_pg;
6391         struct ftrace_page *pg;
6392         struct dyn_ftrace *rec;
6393         unsigned long count;
6394         unsigned long *p;
6395         unsigned long addr;
6396         unsigned long flags = 0; /* Shut up gcc */
6397         int ret = -ENOMEM;
6398
6399         count = end - start;
6400
6401         if (!count)
6402                 return 0;
6403
6404         /*
6405          * Sorting mcount in vmlinux at build time depend on
6406          * CONFIG_BUILDTIME_MCOUNT_SORT, while mcount loc in
6407          * modules can not be sorted at build time.
6408          */
6409         if (!IS_ENABLED(CONFIG_BUILDTIME_MCOUNT_SORT) || mod) {
6410                 sort(start, count, sizeof(*start),
6411                      ftrace_cmp_ips, NULL);
6412         } else {
6413                 test_is_sorted(start, count);
6414         }
6415
6416         start_pg = ftrace_allocate_pages(count);
6417         if (!start_pg)
6418                 return -ENOMEM;
6419
6420         mutex_lock(&ftrace_lock);
6421
6422         /*
6423          * Core and each module needs their own pages, as
6424          * modules will free them when they are removed.
6425          * Force a new page to be allocated for modules.
6426          */
6427         if (!mod) {
6428                 WARN_ON(ftrace_pages || ftrace_pages_start);
6429                 /* First initialization */
6430                 ftrace_pages = ftrace_pages_start = start_pg;
6431         } else {
6432                 if (!ftrace_pages)
6433                         goto out;
6434
6435                 if (WARN_ON(ftrace_pages->next)) {
6436                         /* Hmm, we have free pages? */
6437                         while (ftrace_pages->next)
6438                                 ftrace_pages = ftrace_pages->next;
6439                 }
6440
6441                 ftrace_pages->next = start_pg;
6442         }
6443
6444         p = start;
6445         pg = start_pg;
6446         while (p < end) {
6447                 unsigned long end_offset;
6448                 addr = ftrace_call_adjust(*p++);
6449                 /*
6450                  * Some architecture linkers will pad between
6451                  * the different mcount_loc sections of different
6452                  * object files to satisfy alignments.
6453                  * Skip any NULL pointers.
6454                  */
6455                 if (!addr)
6456                         continue;
6457
6458                 end_offset = (pg->index+1) * sizeof(pg->records[0]);
6459                 if (end_offset > PAGE_SIZE << pg->order) {
6460                         /* We should have allocated enough */
6461                         if (WARN_ON(!pg->next))
6462                                 break;
6463                         pg = pg->next;
6464                 }
6465
6466                 rec = &pg->records[pg->index++];
6467                 rec->ip = addr;
6468         }
6469
6470         /* We should have used all pages */
6471         WARN_ON(pg->next);
6472
6473         /* Assign the last page to ftrace_pages */
6474         ftrace_pages = pg;
6475
6476         /*
6477          * We only need to disable interrupts on start up
6478          * because we are modifying code that an interrupt
6479          * may execute, and the modification is not atomic.
6480          * But for modules, nothing runs the code we modify
6481          * until we are finished with it, and there's no
6482          * reason to cause large interrupt latencies while we do it.
6483          */
6484         if (!mod)
6485                 local_irq_save(flags);
6486         ftrace_update_code(mod, start_pg);
6487         if (!mod)
6488                 local_irq_restore(flags);
6489         ret = 0;
6490  out:
6491         mutex_unlock(&ftrace_lock);
6492
6493         return ret;
6494 }
6495
6496 struct ftrace_mod_func {
6497         struct list_head        list;
6498         char                    *name;
6499         unsigned long           ip;
6500         unsigned int            size;
6501 };
6502
6503 struct ftrace_mod_map {
6504         struct rcu_head         rcu;
6505         struct list_head        list;
6506         struct module           *mod;
6507         unsigned long           start_addr;
6508         unsigned long           end_addr;
6509         struct list_head        funcs;
6510         unsigned int            num_funcs;
6511 };
6512
6513 static int ftrace_get_trampoline_kallsym(unsigned int symnum,
6514                                          unsigned long *value, char *type,
6515                                          char *name, char *module_name,
6516                                          int *exported)
6517 {
6518         struct ftrace_ops *op;
6519
6520         list_for_each_entry_rcu(op, &ftrace_ops_trampoline_list, list) {
6521                 if (!op->trampoline || symnum--)
6522                         continue;
6523                 *value = op->trampoline;
6524                 *type = 't';
6525                 strlcpy(name, FTRACE_TRAMPOLINE_SYM, KSYM_NAME_LEN);
6526                 strlcpy(module_name, FTRACE_TRAMPOLINE_MOD, MODULE_NAME_LEN);
6527                 *exported = 0;
6528                 return 0;
6529         }
6530
6531         return -ERANGE;
6532 }
6533
6534 #if defined(CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS) || defined(CONFIG_MODULES)
6535 /*
6536  * Check if the current ops references the given ip.
6537  *
6538  * If the ops traces all functions, then it was already accounted for.
6539  * If the ops does not trace the current record function, skip it.
6540  * If the ops ignores the function via notrace filter, skip it.
6541  */
6542 static bool
6543 ops_references_ip(struct ftrace_ops *ops, unsigned long ip)
6544 {
6545         /* If ops isn't enabled, ignore it */
6546         if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
6547                 return false;
6548
6549         /* If ops traces all then it includes this function */
6550         if (ops_traces_mod(ops))
6551                 return true;
6552
6553         /* The function must be in the filter */
6554         if (!ftrace_hash_empty(ops->func_hash->filter_hash) &&
6555             !__ftrace_lookup_ip(ops->func_hash->filter_hash, ip))
6556                 return false;
6557
6558         /* If in notrace hash, we ignore it too */
6559         if (ftrace_lookup_ip(ops->func_hash->notrace_hash, ip))
6560                 return false;
6561
6562         return true;
6563 }
6564 #endif
6565
6566 #ifdef CONFIG_MODULES
6567
6568 #define next_to_ftrace_page(p) container_of(p, struct ftrace_page, next)
6569
6570 static LIST_HEAD(ftrace_mod_maps);
6571
6572 static int referenced_filters(struct dyn_ftrace *rec)
6573 {
6574         struct ftrace_ops *ops;
6575         int cnt = 0;
6576
6577         for (ops = ftrace_ops_list; ops != &ftrace_list_end; ops = ops->next) {
6578                 if (ops_references_ip(ops, rec->ip)) {
6579                         if (WARN_ON_ONCE(ops->flags & FTRACE_OPS_FL_DIRECT))
6580                                 continue;
6581                         if (WARN_ON_ONCE(ops->flags & FTRACE_OPS_FL_IPMODIFY))
6582                                 continue;
6583                         cnt++;
6584                         if (ops->flags & FTRACE_OPS_FL_SAVE_REGS)
6585                                 rec->flags |= FTRACE_FL_REGS;
6586                         if (cnt == 1 && ops->trampoline)
6587                                 rec->flags |= FTRACE_FL_TRAMP;
6588                         else
6589                                 rec->flags &= ~FTRACE_FL_TRAMP;
6590                 }
6591         }
6592
6593         return cnt;
6594 }
6595
6596 static void
6597 clear_mod_from_hash(struct ftrace_page *pg, struct ftrace_hash *hash)
6598 {
6599         struct ftrace_func_entry *entry;
6600         struct dyn_ftrace *rec;
6601         int i;
6602
6603         if (ftrace_hash_empty(hash))
6604                 return;
6605
6606         for (i = 0; i < pg->index; i++) {
6607                 rec = &pg->records[i];
6608                 entry = __ftrace_lookup_ip(hash, rec->ip);
6609                 /*
6610                  * Do not allow this rec to match again.
6611                  * Yeah, it may waste some memory, but will be removed
6612                  * if/when the hash is modified again.
6613                  */
6614                 if (entry)
6615                         entry->ip = 0;
6616         }
6617 }
6618
6619 /* Clear any records from hashes */
6620 static void clear_mod_from_hashes(struct ftrace_page *pg)
6621 {
6622         struct trace_array *tr;
6623
6624         mutex_lock(&trace_types_lock);
6625         list_for_each_entry(tr, &ftrace_trace_arrays, list) {
6626                 if (!tr->ops || !tr->ops->func_hash)
6627                         continue;
6628                 mutex_lock(&tr->ops->func_hash->regex_lock);
6629                 clear_mod_from_hash(pg, tr->ops->func_hash->filter_hash);
6630                 clear_mod_from_hash(pg, tr->ops->func_hash->notrace_hash);
6631                 mutex_unlock(&tr->ops->func_hash->regex_lock);
6632         }
6633         mutex_unlock(&trace_types_lock);
6634 }
6635
6636 static void ftrace_free_mod_map(struct rcu_head *rcu)
6637 {
6638         struct ftrace_mod_map *mod_map = container_of(rcu, struct ftrace_mod_map, rcu);
6639         struct ftrace_mod_func *mod_func;
6640         struct ftrace_mod_func *n;
6641
6642         /* All the contents of mod_map are now not visible to readers */
6643         list_for_each_entry_safe(mod_func, n, &mod_map->funcs, list) {
6644                 kfree(mod_func->name);
6645                 list_del(&mod_func->list);
6646                 kfree(mod_func);
6647         }
6648
6649         kfree(mod_map);
6650 }
6651
6652 void ftrace_release_mod(struct module *mod)
6653 {
6654         struct ftrace_mod_map *mod_map;
6655         struct ftrace_mod_map *n;
6656         struct dyn_ftrace *rec;
6657         struct ftrace_page **last_pg;
6658         struct ftrace_page *tmp_page = NULL;
6659         struct ftrace_page *pg;
6660
6661         mutex_lock(&ftrace_lock);
6662
6663         if (ftrace_disabled)
6664                 goto out_unlock;
6665
6666         list_for_each_entry_safe(mod_map, n, &ftrace_mod_maps, list) {
6667                 if (mod_map->mod == mod) {
6668                         list_del_rcu(&mod_map->list);
6669                         call_rcu(&mod_map->rcu, ftrace_free_mod_map);
6670                         break;
6671                 }
6672         }
6673
6674         /*
6675          * Each module has its own ftrace_pages, remove
6676          * them from the list.
6677          */
6678         last_pg = &ftrace_pages_start;
6679         for (pg = ftrace_pages_start; pg; pg = *last_pg) {
6680                 rec = &pg->records[0];
6681                 if (within_module_core(rec->ip, mod) ||
6682                     within_module_init(rec->ip, mod)) {
6683                         /*
6684                          * As core pages are first, the first
6685                          * page should never be a module page.
6686                          */
6687                         if (WARN_ON(pg == ftrace_pages_start))
6688                                 goto out_unlock;
6689
6690                         /* Check if we are deleting the last page */
6691                         if (pg == ftrace_pages)
6692                                 ftrace_pages = next_to_ftrace_page(last_pg);
6693
6694                         ftrace_update_tot_cnt -= pg->index;
6695                         *last_pg = pg->next;
6696
6697                         pg->next = tmp_page;
6698                         tmp_page = pg;
6699                 } else
6700                         last_pg = &pg->next;
6701         }
6702  out_unlock:
6703         mutex_unlock(&ftrace_lock);
6704
6705         for (pg = tmp_page; pg; pg = tmp_page) {
6706
6707                 /* Needs to be called outside of ftrace_lock */
6708                 clear_mod_from_hashes(pg);
6709
6710                 if (pg->records) {
6711                         free_pages((unsigned long)pg->records, pg->order);
6712                         ftrace_number_of_pages -= 1 << pg->order;
6713                 }
6714                 tmp_page = pg->next;
6715                 kfree(pg);
6716                 ftrace_number_of_groups--;
6717         }
6718 }
6719
6720 void ftrace_module_enable(struct module *mod)
6721 {
6722         struct dyn_ftrace *rec;
6723         struct ftrace_page *pg;
6724
6725         mutex_lock(&ftrace_lock);
6726
6727         if (ftrace_disabled)
6728                 goto out_unlock;
6729
6730         /*
6731          * If the tracing is enabled, go ahead and enable the record.
6732          *
6733          * The reason not to enable the record immediately is the
6734          * inherent check of ftrace_make_nop/ftrace_make_call for
6735          * correct previous instructions.  Making first the NOP
6736          * conversion puts the module to the correct state, thus
6737          * passing the ftrace_make_call check.
6738          *
6739          * We also delay this to after the module code already set the
6740          * text to read-only, as we now need to set it back to read-write
6741          * so that we can modify the text.
6742          */
6743         if (ftrace_start_up)
6744                 ftrace_arch_code_modify_prepare();
6745
6746         do_for_each_ftrace_rec(pg, rec) {
6747                 int cnt;
6748                 /*
6749                  * do_for_each_ftrace_rec() is a double loop.
6750                  * module text shares the pg. If a record is
6751                  * not part of this module, then skip this pg,
6752                  * which the "break" will do.
6753                  */
6754                 if (!within_module_core(rec->ip, mod) &&
6755                     !within_module_init(rec->ip, mod))
6756                         break;
6757
6758                 /* Weak functions should still be ignored */
6759                 if (!test_for_valid_rec(rec)) {
6760                         /* Clear all other flags. Should not be enabled anyway */
6761                         rec->flags = FTRACE_FL_DISABLED;
6762                         continue;
6763                 }
6764
6765                 cnt = 0;
6766
6767                 /*
6768                  * When adding a module, we need to check if tracers are
6769                  * currently enabled and if they are, and can trace this record,
6770                  * we need to enable the module functions as well as update the
6771                  * reference counts for those function records.
6772                  */
6773                 if (ftrace_start_up)
6774                         cnt += referenced_filters(rec);
6775
6776                 rec->flags &= ~FTRACE_FL_DISABLED;
6777                 rec->flags += cnt;
6778
6779                 if (ftrace_start_up && cnt) {
6780                         int failed = __ftrace_replace_code(rec, 1);
6781                         if (failed) {
6782                                 ftrace_bug(failed, rec);
6783                                 goto out_loop;
6784                         }
6785                 }
6786
6787         } while_for_each_ftrace_rec();
6788
6789  out_loop:
6790         if (ftrace_start_up)
6791                 ftrace_arch_code_modify_post_process();
6792
6793  out_unlock:
6794         mutex_unlock(&ftrace_lock);
6795
6796         process_cached_mods(mod->name);
6797 }
6798
6799 void ftrace_module_init(struct module *mod)
6800 {
6801         int ret;
6802
6803         if (ftrace_disabled || !mod->num_ftrace_callsites)
6804                 return;
6805
6806         ret = ftrace_process_locs(mod, mod->ftrace_callsites,
6807                                   mod->ftrace_callsites + mod->num_ftrace_callsites);
6808         if (ret)
6809                 pr_warn("ftrace: failed to allocate entries for module '%s' functions\n",
6810                         mod->name);
6811 }
6812
6813 static void save_ftrace_mod_rec(struct ftrace_mod_map *mod_map,
6814                                 struct dyn_ftrace *rec)
6815 {
6816         struct ftrace_mod_func *mod_func;
6817         unsigned long symsize;
6818         unsigned long offset;
6819         char str[KSYM_SYMBOL_LEN];
6820         char *modname;
6821         const char *ret;
6822
6823         ret = kallsyms_lookup(rec->ip, &symsize, &offset, &modname, str);
6824         if (!ret)
6825                 return;
6826
6827         mod_func = kmalloc(sizeof(*mod_func), GFP_KERNEL);
6828         if (!mod_func)
6829                 return;
6830
6831         mod_func->name = kstrdup(str, GFP_KERNEL);
6832         if (!mod_func->name) {
6833                 kfree(mod_func);
6834                 return;
6835         }
6836
6837         mod_func->ip = rec->ip - offset;
6838         mod_func->size = symsize;
6839
6840         mod_map->num_funcs++;
6841
6842         list_add_rcu(&mod_func->list, &mod_map->funcs);
6843 }
6844
6845 static struct ftrace_mod_map *
6846 allocate_ftrace_mod_map(struct module *mod,
6847                         unsigned long start, unsigned long end)
6848 {
6849         struct ftrace_mod_map *mod_map;
6850
6851         mod_map = kmalloc(sizeof(*mod_map), GFP_KERNEL);
6852         if (!mod_map)
6853                 return NULL;
6854
6855         mod_map->mod = mod;
6856         mod_map->start_addr = start;
6857         mod_map->end_addr = end;
6858         mod_map->num_funcs = 0;
6859
6860         INIT_LIST_HEAD_RCU(&mod_map->funcs);
6861
6862         list_add_rcu(&mod_map->list, &ftrace_mod_maps);
6863
6864         return mod_map;
6865 }
6866
6867 static const char *
6868 ftrace_func_address_lookup(struct ftrace_mod_map *mod_map,
6869                            unsigned long addr, unsigned long *size,
6870                            unsigned long *off, char *sym)
6871 {
6872         struct ftrace_mod_func *found_func =  NULL;
6873         struct ftrace_mod_func *mod_func;
6874
6875         list_for_each_entry_rcu(mod_func, &mod_map->funcs, list) {
6876                 if (addr >= mod_func->ip &&
6877                     addr < mod_func->ip + mod_func->size) {
6878                         found_func = mod_func;
6879                         break;
6880                 }
6881         }
6882
6883         if (found_func) {
6884                 if (size)
6885                         *size = found_func->size;
6886                 if (off)
6887                         *off = addr - found_func->ip;
6888                 if (sym)
6889                         strlcpy(sym, found_func->name, KSYM_NAME_LEN);
6890
6891                 return found_func->name;
6892         }
6893
6894         return NULL;
6895 }
6896
6897 const char *
6898 ftrace_mod_address_lookup(unsigned long addr, unsigned long *size,
6899                    unsigned long *off, char **modname, char *sym)
6900 {
6901         struct ftrace_mod_map *mod_map;
6902         const char *ret = NULL;
6903
6904         /* mod_map is freed via call_rcu() */
6905         preempt_disable();
6906         list_for_each_entry_rcu(mod_map, &ftrace_mod_maps, list) {
6907                 ret = ftrace_func_address_lookup(mod_map, addr, size, off, sym);
6908                 if (ret) {
6909                         if (modname)
6910                                 *modname = mod_map->mod->name;
6911                         break;
6912                 }
6913         }
6914         preempt_enable();
6915
6916         return ret;
6917 }
6918
6919 int ftrace_mod_get_kallsym(unsigned int symnum, unsigned long *value,
6920                            char *type, char *name,
6921                            char *module_name, int *exported)
6922 {
6923         struct ftrace_mod_map *mod_map;
6924         struct ftrace_mod_func *mod_func;
6925         int ret;
6926
6927         preempt_disable();
6928         list_for_each_entry_rcu(mod_map, &ftrace_mod_maps, list) {
6929
6930                 if (symnum >= mod_map->num_funcs) {
6931                         symnum -= mod_map->num_funcs;
6932                         continue;
6933                 }
6934
6935                 list_for_each_entry_rcu(mod_func, &mod_map->funcs, list) {
6936                         if (symnum > 1) {
6937                                 symnum--;
6938                                 continue;
6939                         }
6940
6941                         *value = mod_func->ip;
6942                         *type = 'T';
6943                         strlcpy(name, mod_func->name, KSYM_NAME_LEN);
6944                         strlcpy(module_name, mod_map->mod->name, MODULE_NAME_LEN);
6945                         *exported = 1;
6946                         preempt_enable();
6947                         return 0;
6948                 }
6949                 WARN_ON(1);
6950                 break;
6951         }
6952         ret = ftrace_get_trampoline_kallsym(symnum, value, type, name,
6953                                             module_name, exported);
6954         preempt_enable();
6955         return ret;
6956 }
6957
6958 #else
6959 static void save_ftrace_mod_rec(struct ftrace_mod_map *mod_map,
6960                                 struct dyn_ftrace *rec) { }
6961 static inline struct ftrace_mod_map *
6962 allocate_ftrace_mod_map(struct module *mod,
6963                         unsigned long start, unsigned long end)
6964 {
6965         return NULL;
6966 }
6967 int ftrace_mod_get_kallsym(unsigned int symnum, unsigned long *value,
6968                            char *type, char *name, char *module_name,
6969                            int *exported)
6970 {
6971         int ret;
6972
6973         preempt_disable();
6974         ret = ftrace_get_trampoline_kallsym(symnum, value, type, name,
6975                                             module_name, exported);
6976         preempt_enable();
6977         return ret;
6978 }
6979 #endif /* CONFIG_MODULES */
6980
6981 struct ftrace_init_func {
6982         struct list_head list;
6983         unsigned long ip;
6984 };
6985
6986 /* Clear any init ips from hashes */
6987 static void
6988 clear_func_from_hash(struct ftrace_init_func *func, struct ftrace_hash *hash)
6989 {
6990         struct ftrace_func_entry *entry;
6991
6992         entry = ftrace_lookup_ip(hash, func->ip);
6993         /*
6994          * Do not allow this rec to match again.
6995          * Yeah, it may waste some memory, but will be removed
6996          * if/when the hash is modified again.
6997          */
6998         if (entry)
6999                 entry->ip = 0;
7000 }
7001
7002 static void
7003 clear_func_from_hashes(struct ftrace_init_func *func)
7004 {
7005         struct trace_array *tr;
7006
7007         mutex_lock(&trace_types_lock);
7008         list_for_each_entry(tr, &ftrace_trace_arrays, list) {
7009                 if (!tr->ops || !tr->ops->func_hash)
7010                         continue;
7011                 mutex_lock(&tr->ops->func_hash->regex_lock);
7012                 clear_func_from_hash(func, tr->ops->func_hash->filter_hash);
7013                 clear_func_from_hash(func, tr->ops->func_hash->notrace_hash);
7014                 mutex_unlock(&tr->ops->func_hash->regex_lock);
7015         }
7016         mutex_unlock(&trace_types_lock);
7017 }
7018
7019 static void add_to_clear_hash_list(struct list_head *clear_list,
7020                                    struct dyn_ftrace *rec)
7021 {
7022         struct ftrace_init_func *func;
7023
7024         func = kmalloc(sizeof(*func), GFP_KERNEL);
7025         if (!func) {
7026                 MEM_FAIL(1, "alloc failure, ftrace filter could be stale\n");
7027                 return;
7028         }
7029
7030         func->ip = rec->ip;
7031         list_add(&func->list, clear_list);
7032 }
7033
7034 void ftrace_free_mem(struct module *mod, void *start_ptr, void *end_ptr)
7035 {
7036         unsigned long start = (unsigned long)(start_ptr);
7037         unsigned long end = (unsigned long)(end_ptr);
7038         struct ftrace_page **last_pg = &ftrace_pages_start;
7039         struct ftrace_page *pg;
7040         struct dyn_ftrace *rec;
7041         struct dyn_ftrace key;
7042         struct ftrace_mod_map *mod_map = NULL;
7043         struct ftrace_init_func *func, *func_next;
7044         struct list_head clear_hash;
7045
7046         INIT_LIST_HEAD(&clear_hash);
7047
7048         key.ip = start;
7049         key.flags = end;        /* overload flags, as it is unsigned long */
7050
7051         mutex_lock(&ftrace_lock);
7052
7053         /*
7054          * If we are freeing module init memory, then check if
7055          * any tracer is active. If so, we need to save a mapping of
7056          * the module functions being freed with the address.
7057          */
7058         if (mod && ftrace_ops_list != &ftrace_list_end)
7059                 mod_map = allocate_ftrace_mod_map(mod, start, end);
7060
7061         for (pg = ftrace_pages_start; pg; last_pg = &pg->next, pg = *last_pg) {
7062                 if (end < pg->records[0].ip ||
7063                     start >= (pg->records[pg->index - 1].ip + MCOUNT_INSN_SIZE))
7064                         continue;
7065  again:
7066                 rec = bsearch(&key, pg->records, pg->index,
7067                               sizeof(struct dyn_ftrace),
7068                               ftrace_cmp_recs);
7069                 if (!rec)
7070                         continue;
7071
7072                 /* rec will be cleared from hashes after ftrace_lock unlock */
7073                 add_to_clear_hash_list(&clear_hash, rec);
7074
7075                 if (mod_map)
7076                         save_ftrace_mod_rec(mod_map, rec);
7077
7078                 pg->index--;
7079                 ftrace_update_tot_cnt--;
7080                 if (!pg->index) {
7081                         *last_pg = pg->next;
7082                         if (pg->records) {
7083                                 free_pages((unsigned long)pg->records, pg->order);
7084                                 ftrace_number_of_pages -= 1 << pg->order;
7085                         }
7086                         ftrace_number_of_groups--;
7087                         kfree(pg);
7088                         pg = container_of(last_pg, struct ftrace_page, next);
7089                         if (!(*last_pg))
7090                                 ftrace_pages = pg;
7091                         continue;
7092                 }
7093                 memmove(rec, rec + 1,
7094                         (pg->index - (rec - pg->records)) * sizeof(*rec));
7095                 /* More than one function may be in this block */
7096                 goto again;
7097         }
7098         mutex_unlock(&ftrace_lock);
7099
7100         list_for_each_entry_safe(func, func_next, &clear_hash, list) {
7101                 clear_func_from_hashes(func);
7102                 kfree(func);
7103         }
7104 }
7105
7106 void __init ftrace_free_init_mem(void)
7107 {
7108         void *start = (void *)(&__init_begin);
7109         void *end = (void *)(&__init_end);
7110
7111         ftrace_boot_snapshot();
7112
7113         ftrace_free_mem(NULL, start, end);
7114 }
7115
7116 int __init __weak ftrace_dyn_arch_init(void)
7117 {
7118         return 0;
7119 }
7120
7121 void __init ftrace_init(void)
7122 {
7123         extern unsigned long __start_mcount_loc[];
7124         extern unsigned long __stop_mcount_loc[];
7125         unsigned long count, flags;
7126         int ret;
7127
7128         local_irq_save(flags);
7129         ret = ftrace_dyn_arch_init();
7130         local_irq_restore(flags);
7131         if (ret)
7132                 goto failed;
7133
7134         count = __stop_mcount_loc - __start_mcount_loc;
7135         if (!count) {
7136                 pr_info("ftrace: No functions to be traced?\n");
7137                 goto failed;
7138         }
7139
7140         pr_info("ftrace: allocating %ld entries in %ld pages\n",
7141                 count, DIV_ROUND_UP(count, ENTRIES_PER_PAGE));
7142
7143         ret = ftrace_process_locs(NULL,
7144                                   __start_mcount_loc,
7145                                   __stop_mcount_loc);
7146         if (ret) {
7147                 pr_warn("ftrace: failed to allocate entries for functions\n");
7148                 goto failed;
7149         }
7150
7151         pr_info("ftrace: allocated %ld pages with %ld groups\n",
7152                 ftrace_number_of_pages, ftrace_number_of_groups);
7153
7154         last_ftrace_enabled = ftrace_enabled = 1;
7155
7156         set_ftrace_early_filters();
7157
7158         return;
7159  failed:
7160         ftrace_disabled = 1;
7161 }
7162
7163 /* Do nothing if arch does not support this */
7164 void __weak arch_ftrace_update_trampoline(struct ftrace_ops *ops)
7165 {
7166 }
7167
7168 static void ftrace_update_trampoline(struct ftrace_ops *ops)
7169 {
7170         unsigned long trampoline = ops->trampoline;
7171
7172         arch_ftrace_update_trampoline(ops);
7173         if (ops->trampoline && ops->trampoline != trampoline &&
7174             (ops->flags & FTRACE_OPS_FL_ALLOC_TRAMP)) {
7175                 /* Add to kallsyms before the perf events */
7176                 ftrace_add_trampoline_to_kallsyms(ops);
7177                 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_OOL,
7178                                    ops->trampoline, ops->trampoline_size, false,
7179                                    FTRACE_TRAMPOLINE_SYM);
7180                 /*
7181                  * Record the perf text poke event after the ksymbol register
7182                  * event.
7183                  */
7184                 perf_event_text_poke((void *)ops->trampoline, NULL, 0,
7185                                      (void *)ops->trampoline,
7186                                      ops->trampoline_size);
7187         }
7188 }
7189
7190 void ftrace_init_trace_array(struct trace_array *tr)
7191 {
7192         INIT_LIST_HEAD(&tr->func_probes);
7193         INIT_LIST_HEAD(&tr->mod_trace);
7194         INIT_LIST_HEAD(&tr->mod_notrace);
7195 }
7196 #else
7197
7198 struct ftrace_ops global_ops = {
7199         .func                   = ftrace_stub,
7200         .flags                  = FTRACE_OPS_FL_INITIALIZED |
7201                                   FTRACE_OPS_FL_PID,
7202 };
7203
7204 static int __init ftrace_nodyn_init(void)
7205 {
7206         ftrace_enabled = 1;
7207         return 0;
7208 }
7209 core_initcall(ftrace_nodyn_init);
7210
7211 static inline int ftrace_init_dyn_tracefs(struct dentry *d_tracer) { return 0; }
7212 static inline void ftrace_startup_all(int command) { }
7213
7214 static void ftrace_update_trampoline(struct ftrace_ops *ops)
7215 {
7216 }
7217
7218 #endif /* CONFIG_DYNAMIC_FTRACE */
7219
7220 __init void ftrace_init_global_array_ops(struct trace_array *tr)
7221 {
7222         tr->ops = &global_ops;
7223         tr->ops->private = tr;
7224         ftrace_init_trace_array(tr);
7225 }
7226
7227 void ftrace_init_array_ops(struct trace_array *tr, ftrace_func_t func)
7228 {
7229         /* If we filter on pids, update to use the pid function */
7230         if (tr->flags & TRACE_ARRAY_FL_GLOBAL) {
7231                 if (WARN_ON(tr->ops->func != ftrace_stub))
7232                         printk("ftrace ops had %pS for function\n",
7233                                tr->ops->func);
7234         }
7235         tr->ops->func = func;
7236         tr->ops->private = tr;
7237 }
7238
7239 void ftrace_reset_array_ops(struct trace_array *tr)
7240 {
7241         tr->ops->func = ftrace_stub;
7242 }
7243
7244 static nokprobe_inline void
7245 __ftrace_ops_list_func(unsigned long ip, unsigned long parent_ip,
7246                        struct ftrace_ops *ignored, struct ftrace_regs *fregs)
7247 {
7248         struct pt_regs *regs = ftrace_get_regs(fregs);
7249         struct ftrace_ops *op;
7250         int bit;
7251
7252         /*
7253          * The ftrace_test_and_set_recursion() will disable preemption,
7254          * which is required since some of the ops may be dynamically
7255          * allocated, they must be freed after a synchronize_rcu().
7256          */
7257         bit = trace_test_and_set_recursion(ip, parent_ip, TRACE_LIST_START);
7258         if (bit < 0)
7259                 return;
7260
7261         do_for_each_ftrace_op(op, ftrace_ops_list) {
7262                 /* Stub functions don't need to be called nor tested */
7263                 if (op->flags & FTRACE_OPS_FL_STUB)
7264                         continue;
7265                 /*
7266                  * Check the following for each ops before calling their func:
7267                  *  if RCU flag is set, then rcu_is_watching() must be true
7268                  *  Otherwise test if the ip matches the ops filter
7269                  *
7270                  * If any of the above fails then the op->func() is not executed.
7271                  */
7272                 if ((!(op->flags & FTRACE_OPS_FL_RCU) || rcu_is_watching()) &&
7273                     ftrace_ops_test(op, ip, regs)) {
7274                         if (FTRACE_WARN_ON(!op->func)) {
7275                                 pr_warn("op=%p %pS\n", op, op);
7276                                 goto out;
7277                         }
7278                         op->func(ip, parent_ip, op, fregs);
7279                 }
7280         } while_for_each_ftrace_op(op);
7281 out:
7282         trace_clear_recursion(bit);
7283 }
7284
7285 /*
7286  * Some archs only support passing ip and parent_ip. Even though
7287  * the list function ignores the op parameter, we do not want any
7288  * C side effects, where a function is called without the caller
7289  * sending a third parameter.
7290  * Archs are to support both the regs and ftrace_ops at the same time.
7291  * If they support ftrace_ops, it is assumed they support regs.
7292  * If call backs want to use regs, they must either check for regs
7293  * being NULL, or CONFIG_DYNAMIC_FTRACE_WITH_REGS.
7294  * Note, CONFIG_DYNAMIC_FTRACE_WITH_REGS expects a full regs to be saved.
7295  * An architecture can pass partial regs with ftrace_ops and still
7296  * set the ARCH_SUPPORTS_FTRACE_OPS.
7297  *
7298  * In vmlinux.lds.h, ftrace_ops_list_func() is defined to be
7299  * arch_ftrace_ops_list_func.
7300  */
7301 #if ARCH_SUPPORTS_FTRACE_OPS
7302 void arch_ftrace_ops_list_func(unsigned long ip, unsigned long parent_ip,
7303                                struct ftrace_ops *op, struct ftrace_regs *fregs)
7304 {
7305         __ftrace_ops_list_func(ip, parent_ip, NULL, fregs);
7306 }
7307 #else
7308 void arch_ftrace_ops_list_func(unsigned long ip, unsigned long parent_ip)
7309 {
7310         __ftrace_ops_list_func(ip, parent_ip, NULL, NULL);
7311 }
7312 #endif
7313 NOKPROBE_SYMBOL(arch_ftrace_ops_list_func);
7314
7315 /*
7316  * If there's only one function registered but it does not support
7317  * recursion, needs RCU protection, then this function will be called
7318  * by the mcount trampoline.
7319  */
7320 static void ftrace_ops_assist_func(unsigned long ip, unsigned long parent_ip,
7321                                    struct ftrace_ops *op, struct ftrace_regs *fregs)
7322 {
7323         int bit;
7324
7325         bit = trace_test_and_set_recursion(ip, parent_ip, TRACE_LIST_START);
7326         if (bit < 0)
7327                 return;
7328
7329         if (!(op->flags & FTRACE_OPS_FL_RCU) || rcu_is_watching())
7330                 op->func(ip, parent_ip, op, fregs);
7331
7332         trace_clear_recursion(bit);
7333 }
7334 NOKPROBE_SYMBOL(ftrace_ops_assist_func);
7335
7336 /**
7337  * ftrace_ops_get_func - get the function a trampoline should call
7338  * @ops: the ops to get the function for
7339  *
7340  * Normally the mcount trampoline will call the ops->func, but there
7341  * are times that it should not. For example, if the ops does not
7342  * have its own recursion protection, then it should call the
7343  * ftrace_ops_assist_func() instead.
7344  *
7345  * Returns the function that the trampoline should call for @ops.
7346  */
7347 ftrace_func_t ftrace_ops_get_func(struct ftrace_ops *ops)
7348 {
7349         /*
7350          * If the function does not handle recursion or needs to be RCU safe,
7351          * then we need to call the assist handler.
7352          */
7353         if (ops->flags & (FTRACE_OPS_FL_RECURSION |
7354                           FTRACE_OPS_FL_RCU))
7355                 return ftrace_ops_assist_func;
7356
7357         return ops->func;
7358 }
7359
7360 static void
7361 ftrace_filter_pid_sched_switch_probe(void *data, bool preempt,
7362                                      struct task_struct *prev,
7363                                      struct task_struct *next,
7364                                      unsigned int prev_state)
7365 {
7366         struct trace_array *tr = data;
7367         struct trace_pid_list *pid_list;
7368         struct trace_pid_list *no_pid_list;
7369
7370         pid_list = rcu_dereference_sched(tr->function_pids);
7371         no_pid_list = rcu_dereference_sched(tr->function_no_pids);
7372
7373         if (trace_ignore_this_task(pid_list, no_pid_list, next))
7374                 this_cpu_write(tr->array_buffer.data->ftrace_ignore_pid,
7375                                FTRACE_PID_IGNORE);
7376         else
7377                 this_cpu_write(tr->array_buffer.data->ftrace_ignore_pid,
7378                                next->pid);
7379 }
7380
7381 static void
7382 ftrace_pid_follow_sched_process_fork(void *data,
7383                                      struct task_struct *self,
7384                                      struct task_struct *task)
7385 {
7386         struct trace_pid_list *pid_list;
7387         struct trace_array *tr = data;
7388
7389         pid_list = rcu_dereference_sched(tr->function_pids);
7390         trace_filter_add_remove_task(pid_list, self, task);
7391
7392         pid_list = rcu_dereference_sched(tr->function_no_pids);
7393         trace_filter_add_remove_task(pid_list, self, task);
7394 }
7395
7396 static void
7397 ftrace_pid_follow_sched_process_exit(void *data, struct task_struct *task)
7398 {
7399         struct trace_pid_list *pid_list;
7400         struct trace_array *tr = data;
7401
7402         pid_list = rcu_dereference_sched(tr->function_pids);
7403         trace_filter_add_remove_task(pid_list, NULL, task);
7404
7405         pid_list = rcu_dereference_sched(tr->function_no_pids);
7406         trace_filter_add_remove_task(pid_list, NULL, task);
7407 }
7408
7409 void ftrace_pid_follow_fork(struct trace_array *tr, bool enable)
7410 {
7411         if (enable) {
7412                 register_trace_sched_process_fork(ftrace_pid_follow_sched_process_fork,
7413                                                   tr);
7414                 register_trace_sched_process_free(ftrace_pid_follow_sched_process_exit,
7415                                                   tr);
7416         } else {
7417                 unregister_trace_sched_process_fork(ftrace_pid_follow_sched_process_fork,
7418                                                     tr);
7419                 unregister_trace_sched_process_free(ftrace_pid_follow_sched_process_exit,
7420                                                     tr);
7421         }
7422 }
7423
7424 static void clear_ftrace_pids(struct trace_array *tr, int type)
7425 {
7426         struct trace_pid_list *pid_list;
7427         struct trace_pid_list *no_pid_list;
7428         int cpu;
7429
7430         pid_list = rcu_dereference_protected(tr->function_pids,
7431                                              lockdep_is_held(&ftrace_lock));
7432         no_pid_list = rcu_dereference_protected(tr->function_no_pids,
7433                                                 lockdep_is_held(&ftrace_lock));
7434
7435         /* Make sure there's something to do */
7436         if (!pid_type_enabled(type, pid_list, no_pid_list))
7437                 return;
7438
7439         /* See if the pids still need to be checked after this */
7440         if (!still_need_pid_events(type, pid_list, no_pid_list)) {
7441                 unregister_trace_sched_switch(ftrace_filter_pid_sched_switch_probe, tr);
7442                 for_each_possible_cpu(cpu)
7443                         per_cpu_ptr(tr->array_buffer.data, cpu)->ftrace_ignore_pid = FTRACE_PID_TRACE;
7444         }
7445
7446         if (type & TRACE_PIDS)
7447                 rcu_assign_pointer(tr->function_pids, NULL);
7448
7449         if (type & TRACE_NO_PIDS)
7450                 rcu_assign_pointer(tr->function_no_pids, NULL);
7451
7452         /* Wait till all users are no longer using pid filtering */
7453         synchronize_rcu();
7454
7455         if ((type & TRACE_PIDS) && pid_list)
7456                 trace_pid_list_free(pid_list);
7457
7458         if ((type & TRACE_NO_PIDS) && no_pid_list)
7459                 trace_pid_list_free(no_pid_list);
7460 }
7461
7462 void ftrace_clear_pids(struct trace_array *tr)
7463 {
7464         mutex_lock(&ftrace_lock);
7465
7466         clear_ftrace_pids(tr, TRACE_PIDS | TRACE_NO_PIDS);
7467
7468         mutex_unlock(&ftrace_lock);
7469 }
7470
7471 static void ftrace_pid_reset(struct trace_array *tr, int type)
7472 {
7473         mutex_lock(&ftrace_lock);
7474         clear_ftrace_pids(tr, type);
7475
7476         ftrace_update_pid_func();
7477         ftrace_startup_all(0);
7478
7479         mutex_unlock(&ftrace_lock);
7480 }
7481
7482 /* Greater than any max PID */
7483 #define FTRACE_NO_PIDS          (void *)(PID_MAX_LIMIT + 1)
7484
7485 static void *fpid_start(struct seq_file *m, loff_t *pos)
7486         __acquires(RCU)
7487 {
7488         struct trace_pid_list *pid_list;
7489         struct trace_array *tr = m->private;
7490
7491         mutex_lock(&ftrace_lock);
7492         rcu_read_lock_sched();
7493
7494         pid_list = rcu_dereference_sched(tr->function_pids);
7495
7496         if (!pid_list)
7497                 return !(*pos) ? FTRACE_NO_PIDS : NULL;
7498
7499         return trace_pid_start(pid_list, pos);
7500 }
7501
7502 static void *fpid_next(struct seq_file *m, void *v, loff_t *pos)
7503 {
7504         struct trace_array *tr = m->private;
7505         struct trace_pid_list *pid_list = rcu_dereference_sched(tr->function_pids);
7506
7507         if (v == FTRACE_NO_PIDS) {
7508                 (*pos)++;
7509                 return NULL;
7510         }
7511         return trace_pid_next(pid_list, v, pos);
7512 }
7513
7514 static void fpid_stop(struct seq_file *m, void *p)
7515         __releases(RCU)
7516 {
7517         rcu_read_unlock_sched();
7518         mutex_unlock(&ftrace_lock);
7519 }
7520
7521 static int fpid_show(struct seq_file *m, void *v)
7522 {
7523         if (v == FTRACE_NO_PIDS) {
7524                 seq_puts(m, "no pid\n");
7525                 return 0;
7526         }
7527
7528         return trace_pid_show(m, v);
7529 }
7530
7531 static const struct seq_operations ftrace_pid_sops = {
7532         .start = fpid_start,
7533         .next = fpid_next,
7534         .stop = fpid_stop,
7535         .show = fpid_show,
7536 };
7537
7538 static void *fnpid_start(struct seq_file *m, loff_t *pos)
7539         __acquires(RCU)
7540 {
7541         struct trace_pid_list *pid_list;
7542         struct trace_array *tr = m->private;
7543
7544         mutex_lock(&ftrace_lock);
7545         rcu_read_lock_sched();
7546
7547         pid_list = rcu_dereference_sched(tr->function_no_pids);
7548
7549         if (!pid_list)
7550                 return !(*pos) ? FTRACE_NO_PIDS : NULL;
7551
7552         return trace_pid_start(pid_list, pos);
7553 }
7554
7555 static void *fnpid_next(struct seq_file *m, void *v, loff_t *pos)
7556 {
7557         struct trace_array *tr = m->private;
7558         struct trace_pid_list *pid_list = rcu_dereference_sched(tr->function_no_pids);
7559
7560         if (v == FTRACE_NO_PIDS) {
7561                 (*pos)++;
7562                 return NULL;
7563         }
7564         return trace_pid_next(pid_list, v, pos);
7565 }
7566
7567 static const struct seq_operations ftrace_no_pid_sops = {
7568         .start = fnpid_start,
7569         .next = fnpid_next,
7570         .stop = fpid_stop,
7571         .show = fpid_show,
7572 };
7573
7574 static int pid_open(struct inode *inode, struct file *file, int type)
7575 {
7576         const struct seq_operations *seq_ops;
7577         struct trace_array *tr = inode->i_private;
7578         struct seq_file *m;
7579         int ret = 0;
7580
7581         ret = tracing_check_open_get_tr(tr);
7582         if (ret)
7583                 return ret;
7584
7585         if ((file->f_mode & FMODE_WRITE) &&
7586             (file->f_flags & O_TRUNC))
7587                 ftrace_pid_reset(tr, type);
7588
7589         switch (type) {
7590         case TRACE_PIDS:
7591                 seq_ops = &ftrace_pid_sops;
7592                 break;
7593         case TRACE_NO_PIDS:
7594                 seq_ops = &ftrace_no_pid_sops;
7595                 break;
7596         default:
7597                 trace_array_put(tr);
7598                 WARN_ON_ONCE(1);
7599                 return -EINVAL;
7600         }
7601
7602         ret = seq_open(file, seq_ops);
7603         if (ret < 0) {
7604                 trace_array_put(tr);
7605         } else {
7606                 m = file->private_data;
7607                 /* copy tr over to seq ops */
7608                 m->private = tr;
7609         }
7610
7611         return ret;
7612 }
7613
7614 static int
7615 ftrace_pid_open(struct inode *inode, struct file *file)
7616 {
7617         return pid_open(inode, file, TRACE_PIDS);
7618 }
7619
7620 static int
7621 ftrace_no_pid_open(struct inode *inode, struct file *file)
7622 {
7623         return pid_open(inode, file, TRACE_NO_PIDS);
7624 }
7625
7626 static void ignore_task_cpu(void *data)
7627 {
7628         struct trace_array *tr = data;
7629         struct trace_pid_list *pid_list;
7630         struct trace_pid_list *no_pid_list;
7631
7632         /*
7633          * This function is called by on_each_cpu() while the
7634          * event_mutex is held.
7635          */
7636         pid_list = rcu_dereference_protected(tr->function_pids,
7637                                              mutex_is_locked(&ftrace_lock));
7638         no_pid_list = rcu_dereference_protected(tr->function_no_pids,
7639                                                 mutex_is_locked(&ftrace_lock));
7640
7641         if (trace_ignore_this_task(pid_list, no_pid_list, current))
7642                 this_cpu_write(tr->array_buffer.data->ftrace_ignore_pid,
7643                                FTRACE_PID_IGNORE);
7644         else
7645                 this_cpu_write(tr->array_buffer.data->ftrace_ignore_pid,
7646                                current->pid);
7647 }
7648
7649 static ssize_t
7650 pid_write(struct file *filp, const char __user *ubuf,
7651           size_t cnt, loff_t *ppos, int type)
7652 {
7653         struct seq_file *m = filp->private_data;
7654         struct trace_array *tr = m->private;
7655         struct trace_pid_list *filtered_pids;
7656         struct trace_pid_list *other_pids;
7657         struct trace_pid_list *pid_list;
7658         ssize_t ret;
7659
7660         if (!cnt)
7661                 return 0;
7662
7663         mutex_lock(&ftrace_lock);
7664
7665         switch (type) {
7666         case TRACE_PIDS:
7667                 filtered_pids = rcu_dereference_protected(tr->function_pids,
7668                                              lockdep_is_held(&ftrace_lock));
7669                 other_pids = rcu_dereference_protected(tr->function_no_pids,
7670                                              lockdep_is_held(&ftrace_lock));
7671                 break;
7672         case TRACE_NO_PIDS:
7673                 filtered_pids = rcu_dereference_protected(tr->function_no_pids,
7674                                              lockdep_is_held(&ftrace_lock));
7675                 other_pids = rcu_dereference_protected(tr->function_pids,
7676                                              lockdep_is_held(&ftrace_lock));
7677                 break;
7678         default:
7679                 ret = -EINVAL;
7680                 WARN_ON_ONCE(1);
7681                 goto out;
7682         }
7683
7684         ret = trace_pid_write(filtered_pids, &pid_list, ubuf, cnt);
7685         if (ret < 0)
7686                 goto out;
7687
7688         switch (type) {
7689         case TRACE_PIDS:
7690                 rcu_assign_pointer(tr->function_pids, pid_list);
7691                 break;
7692         case TRACE_NO_PIDS:
7693                 rcu_assign_pointer(tr->function_no_pids, pid_list);
7694                 break;
7695         }
7696
7697
7698         if (filtered_pids) {
7699                 synchronize_rcu();
7700                 trace_pid_list_free(filtered_pids);
7701         } else if (pid_list && !other_pids) {
7702                 /* Register a probe to set whether to ignore the tracing of a task */
7703                 register_trace_sched_switch(ftrace_filter_pid_sched_switch_probe, tr);
7704         }
7705
7706         /*
7707          * Ignoring of pids is done at task switch. But we have to
7708          * check for those tasks that are currently running.
7709          * Always do this in case a pid was appended or removed.
7710          */
7711         on_each_cpu(ignore_task_cpu, tr, 1);
7712
7713         ftrace_update_pid_func();
7714         ftrace_startup_all(0);
7715  out:
7716         mutex_unlock(&ftrace_lock);
7717
7718         if (ret > 0)
7719                 *ppos += ret;
7720
7721         return ret;
7722 }
7723
7724 static ssize_t
7725 ftrace_pid_write(struct file *filp, const char __user *ubuf,
7726                  size_t cnt, loff_t *ppos)
7727 {
7728         return pid_write(filp, ubuf, cnt, ppos, TRACE_PIDS);
7729 }
7730
7731 static ssize_t
7732 ftrace_no_pid_write(struct file *filp, const char __user *ubuf,
7733                     size_t cnt, loff_t *ppos)
7734 {
7735         return pid_write(filp, ubuf, cnt, ppos, TRACE_NO_PIDS);
7736 }
7737
7738 static int
7739 ftrace_pid_release(struct inode *inode, struct file *file)
7740 {
7741         struct trace_array *tr = inode->i_private;
7742
7743         trace_array_put(tr);
7744
7745         return seq_release(inode, file);
7746 }
7747
7748 static const struct file_operations ftrace_pid_fops = {
7749         .open           = ftrace_pid_open,
7750         .write          = ftrace_pid_write,
7751         .read           = seq_read,
7752         .llseek         = tracing_lseek,
7753         .release        = ftrace_pid_release,
7754 };
7755
7756 static const struct file_operations ftrace_no_pid_fops = {
7757         .open           = ftrace_no_pid_open,
7758         .write          = ftrace_no_pid_write,
7759         .read           = seq_read,
7760         .llseek         = tracing_lseek,
7761         .release        = ftrace_pid_release,
7762 };
7763
7764 void ftrace_init_tracefs(struct trace_array *tr, struct dentry *d_tracer)
7765 {
7766         trace_create_file("set_ftrace_pid", TRACE_MODE_WRITE, d_tracer,
7767                             tr, &ftrace_pid_fops);
7768         trace_create_file("set_ftrace_notrace_pid", TRACE_MODE_WRITE,
7769                           d_tracer, tr, &ftrace_no_pid_fops);
7770 }
7771
7772 void __init ftrace_init_tracefs_toplevel(struct trace_array *tr,
7773                                          struct dentry *d_tracer)
7774 {
7775         /* Only the top level directory has the dyn_tracefs and profile */
7776         WARN_ON(!(tr->flags & TRACE_ARRAY_FL_GLOBAL));
7777
7778         ftrace_init_dyn_tracefs(d_tracer);
7779         ftrace_profile_tracefs(d_tracer);
7780 }
7781
7782 /**
7783  * ftrace_kill - kill ftrace
7784  *
7785  * This function should be used by panic code. It stops ftrace
7786  * but in a not so nice way. If you need to simply kill ftrace
7787  * from a non-atomic section, use ftrace_kill.
7788  */
7789 void ftrace_kill(void)
7790 {
7791         ftrace_disabled = 1;
7792         ftrace_enabled = 0;
7793         ftrace_trace_function = ftrace_stub;
7794 }
7795
7796 /**
7797  * ftrace_is_dead - Test if ftrace is dead or not.
7798  *
7799  * Returns 1 if ftrace is "dead", zero otherwise.
7800  */
7801 int ftrace_is_dead(void)
7802 {
7803         return ftrace_disabled;
7804 }
7805
7806 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
7807 /*
7808  * When registering ftrace_ops with IPMODIFY, it is necessary to make sure
7809  * it doesn't conflict with any direct ftrace_ops. If there is existing
7810  * direct ftrace_ops on a kernel function being patched, call
7811  * FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER on it to enable sharing.
7812  *
7813  * @ops:     ftrace_ops being registered.
7814  *
7815  * Returns:
7816  *         0 on success;
7817  *         Negative on failure.
7818  */
7819 static int prepare_direct_functions_for_ipmodify(struct ftrace_ops *ops)
7820 {
7821         struct ftrace_func_entry *entry;
7822         struct ftrace_hash *hash;
7823         struct ftrace_ops *op;
7824         int size, i, ret;
7825
7826         lockdep_assert_held_once(&direct_mutex);
7827
7828         if (!(ops->flags & FTRACE_OPS_FL_IPMODIFY))
7829                 return 0;
7830
7831         hash = ops->func_hash->filter_hash;
7832         size = 1 << hash->size_bits;
7833         for (i = 0; i < size; i++) {
7834                 hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
7835                         unsigned long ip = entry->ip;
7836                         bool found_op = false;
7837
7838                         mutex_lock(&ftrace_lock);
7839                         do_for_each_ftrace_op(op, ftrace_ops_list) {
7840                                 if (!(op->flags & FTRACE_OPS_FL_DIRECT))
7841                                         continue;
7842                                 if (ops_references_ip(op, ip)) {
7843                                         found_op = true;
7844                                         break;
7845                                 }
7846                         } while_for_each_ftrace_op(op);
7847                         mutex_unlock(&ftrace_lock);
7848
7849                         if (found_op) {
7850                                 if (!op->ops_func)
7851                                         return -EBUSY;
7852
7853                                 ret = op->ops_func(op, FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER);
7854                                 if (ret)
7855                                         return ret;
7856                         }
7857                 }
7858         }
7859
7860         return 0;
7861 }
7862
7863 /*
7864  * Similar to prepare_direct_functions_for_ipmodify, clean up after ops
7865  * with IPMODIFY is unregistered. The cleanup is optional for most DIRECT
7866  * ops.
7867  */
7868 static void cleanup_direct_functions_after_ipmodify(struct ftrace_ops *ops)
7869 {
7870         struct ftrace_func_entry *entry;
7871         struct ftrace_hash *hash;
7872         struct ftrace_ops *op;
7873         int size, i;
7874
7875         if (!(ops->flags & FTRACE_OPS_FL_IPMODIFY))
7876                 return;
7877
7878         mutex_lock(&direct_mutex);
7879
7880         hash = ops->func_hash->filter_hash;
7881         size = 1 << hash->size_bits;
7882         for (i = 0; i < size; i++) {
7883                 hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
7884                         unsigned long ip = entry->ip;
7885                         bool found_op = false;
7886
7887                         mutex_lock(&ftrace_lock);
7888                         do_for_each_ftrace_op(op, ftrace_ops_list) {
7889                                 if (!(op->flags & FTRACE_OPS_FL_DIRECT))
7890                                         continue;
7891                                 if (ops_references_ip(op, ip)) {
7892                                         found_op = true;
7893                                         break;
7894                                 }
7895                         } while_for_each_ftrace_op(op);
7896                         mutex_unlock(&ftrace_lock);
7897
7898                         /* The cleanup is optional, ignore any errors */
7899                         if (found_op && op->ops_func)
7900                                 op->ops_func(op, FTRACE_OPS_CMD_DISABLE_SHARE_IPMODIFY_PEER);
7901                 }
7902         }
7903         mutex_unlock(&direct_mutex);
7904 }
7905
7906 #define lock_direct_mutex()     mutex_lock(&direct_mutex)
7907 #define unlock_direct_mutex()   mutex_unlock(&direct_mutex)
7908
7909 #else  /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS */
7910
7911 static int prepare_direct_functions_for_ipmodify(struct ftrace_ops *ops)
7912 {
7913         return 0;
7914 }
7915
7916 static void cleanup_direct_functions_after_ipmodify(struct ftrace_ops *ops)
7917 {
7918 }
7919
7920 #define lock_direct_mutex()     do { } while (0)
7921 #define unlock_direct_mutex()   do { } while (0)
7922
7923 #endif  /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS */
7924
7925 /*
7926  * Similar to register_ftrace_function, except we don't lock direct_mutex.
7927  */
7928 static int register_ftrace_function_nolock(struct ftrace_ops *ops)
7929 {
7930         int ret;
7931
7932         ftrace_ops_init(ops);
7933
7934         mutex_lock(&ftrace_lock);
7935
7936         ret = ftrace_startup(ops, 0);
7937
7938         mutex_unlock(&ftrace_lock);
7939
7940         return ret;
7941 }
7942
7943 /**
7944  * register_ftrace_function - register a function for profiling
7945  * @ops:        ops structure that holds the function for profiling.
7946  *
7947  * Register a function to be called by all functions in the
7948  * kernel.
7949  *
7950  * Note: @ops->func and all the functions it calls must be labeled
7951  *       with "notrace", otherwise it will go into a
7952  *       recursive loop.
7953  */
7954 int register_ftrace_function(struct ftrace_ops *ops)
7955 {
7956         int ret;
7957
7958         lock_direct_mutex();
7959         ret = prepare_direct_functions_for_ipmodify(ops);
7960         if (ret < 0)
7961                 goto out_unlock;
7962
7963         ret = register_ftrace_function_nolock(ops);
7964
7965 out_unlock:
7966         unlock_direct_mutex();
7967         return ret;
7968 }
7969 EXPORT_SYMBOL_GPL(register_ftrace_function);
7970
7971 /**
7972  * unregister_ftrace_function - unregister a function for profiling.
7973  * @ops:        ops structure that holds the function to unregister
7974  *
7975  * Unregister a function that was added to be called by ftrace profiling.
7976  */
7977 int unregister_ftrace_function(struct ftrace_ops *ops)
7978 {
7979         int ret;
7980
7981         mutex_lock(&ftrace_lock);
7982         ret = ftrace_shutdown(ops, 0);
7983         mutex_unlock(&ftrace_lock);
7984
7985         cleanup_direct_functions_after_ipmodify(ops);
7986         return ret;
7987 }
7988 EXPORT_SYMBOL_GPL(unregister_ftrace_function);
7989
7990 static int symbols_cmp(const void *a, const void *b)
7991 {
7992         const char **str_a = (const char **) a;
7993         const char **str_b = (const char **) b;
7994
7995         return strcmp(*str_a, *str_b);
7996 }
7997
7998 struct kallsyms_data {
7999         unsigned long *addrs;
8000         const char **syms;
8001         size_t cnt;
8002         size_t found;
8003 };
8004
8005 /* This function gets called for all kernel and module symbols
8006  * and returns 1 in case we resolved all the requested symbols,
8007  * 0 otherwise.
8008  */
8009 static int kallsyms_callback(void *data, const char *name,
8010                              struct module *mod, unsigned long addr)
8011 {
8012         struct kallsyms_data *args = data;
8013         const char **sym;
8014         int idx;
8015
8016         sym = bsearch(&name, args->syms, args->cnt, sizeof(*args->syms), symbols_cmp);
8017         if (!sym)
8018                 return 0;
8019
8020         idx = sym - args->syms;
8021         if (args->addrs[idx])
8022                 return 0;
8023
8024         if (!ftrace_location(addr))
8025                 return 0;
8026
8027         args->addrs[idx] = addr;
8028         args->found++;
8029         return args->found == args->cnt ? 1 : 0;
8030 }
8031
8032 /**
8033  * ftrace_lookup_symbols - Lookup addresses for array of symbols
8034  *
8035  * @sorted_syms: array of symbols pointers symbols to resolve,
8036  * must be alphabetically sorted
8037  * @cnt: number of symbols/addresses in @syms/@addrs arrays
8038  * @addrs: array for storing resulting addresses
8039  *
8040  * This function looks up addresses for array of symbols provided in
8041  * @syms array (must be alphabetically sorted) and stores them in
8042  * @addrs array, which needs to be big enough to store at least @cnt
8043  * addresses.
8044  *
8045  * This function returns 0 if all provided symbols are found,
8046  * -ESRCH otherwise.
8047  */
8048 int ftrace_lookup_symbols(const char **sorted_syms, size_t cnt, unsigned long *addrs)
8049 {
8050         struct kallsyms_data args;
8051         int found_all;
8052
8053         memset(addrs, 0, sizeof(*addrs) * cnt);
8054         args.addrs = addrs;
8055         args.syms = sorted_syms;
8056         args.cnt = cnt;
8057         args.found = 0;
8058
8059         found_all = kallsyms_on_each_symbol(kallsyms_callback, &args);
8060         if (found_all)
8061                 return 0;
8062         found_all = module_kallsyms_on_each_symbol(NULL, kallsyms_callback, &args);
8063         return found_all ? 0 : -ESRCH;
8064 }
8065
8066 #ifdef CONFIG_SYSCTL
8067
8068 #ifdef CONFIG_DYNAMIC_FTRACE
8069 static void ftrace_startup_sysctl(void)
8070 {
8071         int command;
8072
8073         if (unlikely(ftrace_disabled))
8074                 return;
8075
8076         /* Force update next time */
8077         saved_ftrace_func = NULL;
8078         /* ftrace_start_up is true if we want ftrace running */
8079         if (ftrace_start_up) {
8080                 command = FTRACE_UPDATE_CALLS;
8081                 if (ftrace_graph_active)
8082                         command |= FTRACE_START_FUNC_RET;
8083                 ftrace_startup_enable(command);
8084         }
8085 }
8086
8087 static void ftrace_shutdown_sysctl(void)
8088 {
8089         int command;
8090
8091         if (unlikely(ftrace_disabled))
8092                 return;
8093
8094         /* ftrace_start_up is true if ftrace is running */
8095         if (ftrace_start_up) {
8096                 command = FTRACE_DISABLE_CALLS;
8097                 if (ftrace_graph_active)
8098                         command |= FTRACE_STOP_FUNC_RET;
8099                 ftrace_run_update_code(command);
8100         }
8101 }
8102 #else
8103 # define ftrace_startup_sysctl()       do { } while (0)
8104 # define ftrace_shutdown_sysctl()      do { } while (0)
8105 #endif /* CONFIG_DYNAMIC_FTRACE */
8106
8107 static bool is_permanent_ops_registered(void)
8108 {
8109         struct ftrace_ops *op;
8110
8111         do_for_each_ftrace_op(op, ftrace_ops_list) {
8112                 if (op->flags & FTRACE_OPS_FL_PERMANENT)
8113                         return true;
8114         } while_for_each_ftrace_op(op);
8115
8116         return false;
8117 }
8118
8119 static int
8120 ftrace_enable_sysctl(struct ctl_table *table, int write,
8121                      void *buffer, size_t *lenp, loff_t *ppos)
8122 {
8123         int ret = -ENODEV;
8124
8125         mutex_lock(&ftrace_lock);
8126
8127         if (unlikely(ftrace_disabled))
8128                 goto out;
8129
8130         ret = proc_dointvec(table, write, buffer, lenp, ppos);
8131
8132         if (ret || !write || (last_ftrace_enabled == !!ftrace_enabled))
8133                 goto out;
8134
8135         if (ftrace_enabled) {
8136
8137                 /* we are starting ftrace again */
8138                 if (rcu_dereference_protected(ftrace_ops_list,
8139                         lockdep_is_held(&ftrace_lock)) != &ftrace_list_end)
8140                         update_ftrace_function();
8141
8142                 ftrace_startup_sysctl();
8143
8144         } else {
8145                 if (is_permanent_ops_registered()) {
8146                         ftrace_enabled = true;
8147                         ret = -EBUSY;
8148                         goto out;
8149                 }
8150
8151                 /* stopping ftrace calls (just send to ftrace_stub) */
8152                 ftrace_trace_function = ftrace_stub;
8153
8154                 ftrace_shutdown_sysctl();
8155         }
8156
8157         last_ftrace_enabled = !!ftrace_enabled;
8158  out:
8159         mutex_unlock(&ftrace_lock);
8160         return ret;
8161 }
8162
8163 static struct ctl_table ftrace_sysctls[] = {
8164         {
8165                 .procname       = "ftrace_enabled",
8166                 .data           = &ftrace_enabled,
8167                 .maxlen         = sizeof(int),
8168                 .mode           = 0644,
8169                 .proc_handler   = ftrace_enable_sysctl,
8170         },
8171         {}
8172 };
8173
8174 static int __init ftrace_sysctl_init(void)
8175 {
8176         register_sysctl_init("kernel", ftrace_sysctls);
8177         return 0;
8178 }
8179 late_initcall(ftrace_sysctl_init);
8180 #endif