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